如何在Python中将彩色文本输出到终端?
当前回答
我是Python新手,每次我发现像这样的主题时都很兴奋。但这次(突然)我觉得我有话要说。尤其是因为几分钟前,我在Python中发现了一件令人惊叹的事情(至少对我来说是这样):
上下文管理器
from contextlib import contextmanager
# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'
@contextmanager
def printESC(prefix, color, text):
print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
yield
print("{prefix}0m".format(prefix=prefix))
with printESC('\x1B[', REDFC, 'Colored Text'):
pass
实例
或者就像这样:
# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'
def printESC(prefix, color, text):
print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
print("{prefix}0m".format(prefix=prefix))
printESC('\x1B[', REDFC, 'Colored Text')
其他回答
您可以使用pygments模块来执行此操作。例如:
from pygments import console
print(pygments.console.colorize("red", "This text is red."))
这不允许您为终端提供十六进制颜色,但您可以尝试许多内置颜色,如“蓝色”、“深绿色”、“黄色”等。
我最终做了这个,我觉得这是最干净的:
formatters = {
'RED': '\033[91m',
'GREEN': '\033[92m',
'END': '\033[0m',
}
print 'Master is currently {RED}red{END}!'.format(**formatters)
print 'Help make master {GREEN}green{END} again!'.format(**formatters)
如果您使用的是Windows,那么就在这里!
# Display text on a Windows console
# Windows XP with Python 2.7 or Python 3.2
from ctypes import windll
# Needed for Python2/Python3 diff
try:
input = raw_input
except:
pass
STD_OUTPUT_HANDLE = -11
stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# Look at the output and select the color you want.
# For instance, hex E is yellow on black.
# Hex 1E is yellow on blue.
# Hex 2E is yellow on green and so on.
for color in range(0, 75):
windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)
print("%X --> %s" % (color, "Have a fine day!"))
input("Press Enter to go on ... ")
这里有一种更有效的方法。
# Colours
pure_red = "\033[0;31m"
dark_green = "\033[0;32m"
orange = "\033[0;33m"
dark_blue = "\033[0;34m"
bright_purple = "\033[0;35m"
dark_cyan = "\033[0;36m"
dull_white = "\033[0;37m"
pure_black = "\033[0;30m"
bright_red = "\033[0;91m"
light_green = "\033[0;92m"
yellow = "\033[0;93m"
bright_blue = "\033[0;94m"
magenta = "\033[0;95m"
light_cyan = "\033[0;96m"
bright_black = "\033[0;90m"
bright_white = "\033[0;97m"
cyan_back = "\033[0;46m"
purple_back = "\033[0;45m"
white_back = "\033[0;47m"
blue_back = "\033[0;44m"
orange_back = "\033[0;43m"
green_back = "\033[0;42m"
pink_back = "\033[0;41m"
grey_back = "\033[0;40m"
grey = '\033[38;4;236m'
bold = "\033[1m"
underline = "\033[4m"
italic = "\033[3m"
darken = "\033[2m"
invisible = '\033[08m'
reverse_colour = '\033[07m'
reset_colour = '\033[0m'
grey = "\x1b[90m"
用户手册
reverseColor表示您反转刚刚选择的颜色,但处于高亮模式(默认为白色)。pink_back(green_back等…带有back的)表示它以粉色突出显示(基于名称)。reset_colour重置颜色(详见图1)。
我相信我不需要解释太多,因为它列在变量名中。
如果您想尝试代码,请转到replit IDE测试代码。示例代码在这里
代码(图1):
输出(图2):
这个答案试图通过使用正则表达式为文本块中的关键字着色来扩展将着色文本写入终端的概念。
这个答案还使用了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输出
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行