如何在Python中将彩色文本输出到终端?
当前回答
您可以使用pygments模块来执行此操作。例如:
from pygments import console
print(pygments.console.colorize("red", "This text is red."))
这不允许您为终端提供十六进制颜色,但您可以尝试许多内置颜色,如“蓝色”、“深绿色”、“黄色”等。
其他回答
我编写了一个在PyPI上可用的库,它有一个遵循标准打印函数的简单API。
你可以用pip安装着色来安装它。
import coloring
# Directly use print-like functions
coloring.print_red('Hello', 12)
coloring.print_green('Hey', end="", sep=";")
print()
# Get str as return
print(coloring.red('hello'))
# Use the generic colorize function
print(coloring.colorize("I'm red", "red")) # Using color names
print(coloring.colorize("I'm green", (0, 255, 0))) # Using RGB colors
print(coloring.colorize("I'm blue", "#0000ff")) # Using hex colors
# Or using styles (underline, bold, italic, ...)
print(coloring.colorize('Hello', 'red', s='ub')) # underline and bold
执行代码:
您可以在此处查看所有功能:https://github.com/Nazime/coloring.
这个答案试图通过使用正则表达式为文本块中的关键字着色来扩展将着色文本写入终端的概念。
这个答案还使用了Python库Rich,在前面的问题答案中简要介绍了它。在这个答案中,我使用函数rich.color.ANSI_color_NAMES获取一个随机的颜色列表,用于突出显示预定义的搜索项。
import random
import re as regex
from rich import color
from rich import print
def create_dynamic_regex(search_words):
"""
This function is used to create a dynamic regular expression
string and a list of random colors. Both these elements will
be used in the function colorize_text()
:param search_words: list of search terms
:return: regular expression search string and a list of colors
:rtype: string, list
"""
colors_required = create_list_of_colors(len(search_words))
number_of_search_words = len(search_words)
combined_string = ''
for search_word in search_words:
number_of_search_words -= 1
if number_of_search_words != 0:
current_string = ''.join(r'(\b' + search_word + r'\b)|')
combined_string = (combined_string + current_string)
elif number_of_search_words == 0:
current_string = ''.join(r'(\b' + search_word + r'\b)')
combined_string = (combined_string + current_string)
return combined_string, colors_required
def random_color():
"""
This function is used to create a random color using the
Python package rich.
:return: color name
:rtype: string
"""
selected_color = random.choice(list(color.ANSI_COLOR_NAMES.keys()))
return selected_color
def create_list_of_colors(number_of_colors):
"""
This function is used to generate a list of colors,
which will be used in the function colorize_text()
:param number_of_colors:
:return: list of colors
:rtype: list
"""
list_of_colors = [random_color() for _ in range(number_of_colors)]
return list_of_colors
def colorize_text(text, regex_string, array_of_colors):
"""
This function is used to colorize specific words in a text string.
:param text: text string potentially containing specific words to colorize.
:param regex_string: regular expression search string
:param array_of_colors: list of colors
:return: colorized text
:rtype: string
"""
available_colors = array_of_colors
word_regex = regex.compile(f"{regex_string}", regex.IGNORECASE)
i = 0
output = ""
for word in word_regex.finditer(text):
get_color = available_colors[word.lastindex - 1]
output += "".join([text[i:word.start()],
"[%s]" % available_colors[word.lastindex - 1],
text[word.start():word.end()], "[/%s]" % available_colors[word.lastindex - 1]])
i = word.end()
return ''.join([output, text[word.end():]])
def generate_console_output(text_to_search, words_to_find):
"""
This function is used generate colorized text that will
be outputting to the console.
:param text_to_search: text string potentially containing specific words to colorize.
:param words_to_find: list of search terms.
:return: A string containing colorized words.
:rtype: string
"""
search_terms, colors = create_dynamic_regex(words_to_find)
colorize_html = colorize_text(text_to_search, search_terms, colors)
print(colorize_html)
text = "The dog chased the cat that was looking for the mouse that the dog was playing with."
words = ['dog', 'cat', 'mouse']
generate_console_output(text, words)
以下是上述代码的打印输出:
我创建了两个用于为文本着色的GIST。
彩色文本终端输出彩色文本HTML输出
打印一个开始颜色/样式的字符串,然后是字符串,然后以'\x1b[0m'结束颜色/样式更改:
print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
使用以下代码获取shell文本的格式选项表:
def print_format_table():
"""
prints table of formatted text format options
"""
for style in range(8):
for fg in range(30,38):
s1 = ''
for bg in range(40,48):
format = ';'.join([str(style), str(fg), str(bg)])
s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
print(s1)
print('\n')
print_format_table()
亮-暗示例(完整)
暗-亮示例(部分)
参考:https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
基于joeld的答案,使用https://pypi.python.org/pypi/lazyme 管道安装-U lazyme:
from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc
截图:
使用新的格式化程序对color_print进行一些更新,例如:
>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter,
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']
注意:斜体、快速闪烁和删除线可能不适用于所有终端,也不适用于Mac和Ubuntu。
例如。,
>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar
截图:
我最喜欢的方式是使用祝福库(完整披露:我写的)。例如:
from blessings import Terminal
t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')
要打印彩色砖,最可靠的方法是使用背景色打印空间。我使用此技术绘制鼻子进度条:
print t.on_green(' ')
您还可以在特定位置打印:
with t.location(0, 5):
print t.on_yellow(' ')
如果你必须在游戏过程中使用其他终端功能,你也可以这样做。您可以使用Python的标准字符串格式来保持其可读性:
print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)
Blessings的优点在于它能在各种终端上工作,而不仅仅是ANSI颜色的终端。它还将不可读的转义序列排除在代码之外,同时保持使用简洁。玩得高兴
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行