如何在Python中将彩色文本输出到终端?
当前回答
这个答案试图通过使用正则表达式为文本块中的关键字着色来扩展将着色文本写入终端的概念。
这个答案还使用了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输出
其他回答
这里有一个快速类,它包装了一个打印功能,可以快速添加颜色,而无需安装其他软件包。
class PrintColored:
DEFAULT = '\033[0m'
# Styles
BOLD = '\033[1m'
ITALIC = '\033[3m'
UNDERLINE = '\033[4m'
UNDERLINE_THICK = '\033[21m'
HIGHLIGHTED = '\033[7m'
HIGHLIGHTED_BLACK = '\033[40m'
HIGHLIGHTED_RED = '\033[41m'
HIGHLIGHTED_GREEN = '\033[42m'
HIGHLIGHTED_YELLOW = '\033[43m'
HIGHLIGHTED_BLUE = '\033[44m'
HIGHLIGHTED_PURPLE = '\033[45m'
HIGHLIGHTED_CYAN = '\033[46m'
HIGHLIGHTED_GREY = '\033[47m'
HIGHLIGHTED_GREY_LIGHT = '\033[100m'
HIGHLIGHTED_RED_LIGHT = '\033[101m'
HIGHLIGHTED_GREEN_LIGHT = '\033[102m'
HIGHLIGHTED_YELLOW_LIGHT = '\033[103m'
HIGHLIGHTED_BLUE_LIGHT = '\033[104m'
HIGHLIGHTED_PURPLE_LIGHT = '\033[105m'
HIGHLIGHTED_CYAN_LIGHT = '\033[106m'
HIGHLIGHTED_WHITE_LIGHT = '\033[107m'
STRIKE_THROUGH = '\033[9m'
MARGIN_1 = '\033[51m'
MARGIN_2 = '\033[52m' # seems equal to MARGIN_1
# colors
BLACK = '\033[30m'
RED_DARK = '\033[31m'
GREEN_DARK = '\033[32m'
YELLOW_DARK = '\033[33m'
BLUE_DARK = '\033[34m'
PURPLE_DARK = '\033[35m'
CYAN_DARK = '\033[36m'
GREY_DARK = '\033[37m'
BLACK_LIGHT = '\033[90m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[96m'
def __init__(self):
self.print_original = print # old value to the original print function
self.current_color = self.DEFAULT
def __call__(self,
*values: object, sep: str | None = None,
end: str | None = None,
file: str | None = None,
flush: bool = False,
color: str|None = None,
default_color: str|None = None,
):
if default_color:
self.current_color = default_color
default = self.current_color
if color:
values = (color, *values, default) # wrap the content within a selected color an a default
else:
values = (*values, default) # wrap the content within a selected color an a default
self.print_original(*values, end=end, file=file, flush=flush)
用法
class PrintColored:
DEFAULT = '\033[0m'
# Styles
BOLD = '\033[1m'
ITALIC = '\033[3m'
UNDERLINE = '\033[4m'
UNDERLINE_THICK = '\033[21m'
HIGHLIGHTED = '\033[7m'
HIGHLIGHTED_BLACK = '\033[40m'
HIGHLIGHTED_RED = '\033[41m'
HIGHLIGHTED_GREEN = '\033[42m'
HIGHLIGHTED_YELLOW = '\033[43m'
HIGHLIGHTED_BLUE = '\033[44m'
HIGHLIGHTED_PURPLE = '\033[45m'
HIGHLIGHTED_CYAN = '\033[46m'
HIGHLIGHTED_GREY = '\033[47m'
HIGHLIGHTED_GREY_LIGHT = '\033[100m'
HIGHLIGHTED_RED_LIGHT = '\033[101m'
HIGHLIGHTED_GREEN_LIGHT = '\033[102m'
HIGHLIGHTED_YELLOW_LIGHT = '\033[103m'
HIGHLIGHTED_BLUE_LIGHT = '\033[104m'
HIGHLIGHTED_PURPLE_LIGHT = '\033[105m'
HIGHLIGHTED_CYAN_LIGHT = '\033[106m'
HIGHLIGHTED_WHITE_LIGHT = '\033[107m'
STRIKE_THROUGH = '\033[9m'
MARGIN_1 = '\033[51m'
MARGIN_2 = '\033[52m' # seems equal to MARGIN_1
# colors
BLACK = '\033[30m'
RED_DARK = '\033[31m'
GREEN_DARK = '\033[32m'
YELLOW_DARK = '\033[33m'
BLUE_DARK = '\033[34m'
PURPLE_DARK = '\033[35m'
CYAN_DARK = '\033[36m'
GREY_DARK = '\033[37m'
BLACK_LIGHT = '\033[90m'
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[96m'
def __init__(self):
self.print_original = print # old value to the original print function
self.current_color = self.DEFAULT
def __call__(self,
*values: object, sep: str | None = None,
end: str | None = None,
file: str | None = None,
flush: bool = False,
color: str|None = None,
default_color: str|None = None,
):
if default_color:
self.current_color = default_color
default = self.current_color
if color:
values = (color, *values, default) # wrap the content within a selected color an a default
else:
values = (*values, default) # wrap the content within a selected color an a default
self.print_original(*values, end=end, file=file, flush=flush)
if __name__ == '__main__':
print = PrintColored()
print("Hello world - default")
print("Hello world - Bold", color=print.BOLD)
print("Hello world - Italic", color=print.ITALIC)
print("Hello world - Underline", color=print.UNDERLINE)
print("Hello world - UNDERLINE_THICK", color=print.UNDERLINE_THICK)
print("Hello world - HighLithted", color=print.HIGHLIGHTED)
print("Hello world - HIGHLIGHTED_BLACK", color=print.HIGHLIGHTED_BLACK)
print("Hello world - HIGHLIGHTED_RED", color=print.HIGHLIGHTED_RED)
print("Hello world - HIGHLIGHTED_GREEN", color=print.HIGHLIGHTED_GREEN)
print("Hello world - HIGHLIGHTED_YELLOW", color=print.HIGHLIGHTED_YELLOW)
print("Hello world - HIGHLIGHTED_BLUE", color=print.HIGHLIGHTED_BLUE)
print("Hello world - HIGHLIGHTED_PURPLE", color=print.HIGHLIGHTED_PURPLE)
print("Hello world - HIGHLIGHTED_CYAN", color=print.HIGHLIGHTED_CYAN)
print("Hello world - HIGHLIGHTED_GREY", color=print.HIGHLIGHTED_GREY)
print("Hello world - HIGHLIGHTED_GREY_LIGHT", color=print.HIGHLIGHTED_GREY_LIGHT)
print("Hello world - HIGHLIGHTED_RED_LIGHT", color=print.HIGHLIGHTED_RED_LIGHT)
print("Hello world - HIGHLIGHTED_GREEN_LIGHT", color=print.HIGHLIGHTED_GREEN_LIGHT)
print("Hello world - HIGHLIGHTED_YELLOW_LIGHT", color=print.HIGHLIGHTED_YELLOW_LIGHT)
print("Hello world - HIGHLIGHTED_BLUE_LIGHT", color=print.HIGHLIGHTED_BLUE_LIGHT)
print("Hello world - HIGHLIGHTED_PURPLE_LIGHT", color=print.HIGHLIGHTED_PURPLE_LIGHT)
print("Hello world - HIGHLIGHTED_CYAN_LIGHT", color=print.HIGHLIGHTED_CYAN_LIGHT)
print("Hello world - HIGHLIGHTED_WHITE_LIGHT", color=print.HIGHLIGHTED_WHITE_LIGHT)
print("Hello world - STRIKE_THROUGH", color=print.STRIKE_THROUGH)
print("Hello world - MARGIN_1", color=print.MARGIN_1)
print("Hello world - MARGIN_2", color=print.MARGIN_2)
print("Hello world - BLACK", color=print.BLACK)
print("Hello world - RED_DARK", color=print.RED_DARK)
print("Hello world - GREEN_DARK", color=print.GREEN_DARK)
print("Hello world - YELLOW_DARK", color=print.YELLOW_DARK)
print("Hello world - BLUE_DARK", color=print.BLUE_DARK)
print("Hello world - PURPLE_DARK", color=print.PURPLE_DARK)
print("Hello world - CYAN_DARK", color=print.CYAN_DARK)
print("Hello world - GREY_DARK", color=print.GREY_DARK)
print("Hello world - BLACK_LIGHT", color=print.BLACK_LIGHT)
print("Hello world - BLACK_LIGHT", color=print.BLACK_LIGHT)
print("Hello world - RED", color=print.RED)
print("Hello world - GREEN", color=print.GREEN)
print("Hello world - YELLOW", color=print.YELLOW)
print("Hello world - BLUE", color=print.BLUE)
print("Hello world - PURPLE", color=print.PURPLE)
print("Hello world - CYAN", color=print.CYAN)
print("Hello world - WHITE", color=print.WHITE)
# Back to normal
print("", default_color=print.DEFAULT)
print("Hello world - default")
输出
这里有一个简单的函数,我使用它来打印彩色文本消息,而不必记住ANSI代码,而是使用标准RGB元组来定义前景和背景颜色。
def print_in_color(txt_msg, fore_tuple, back_tuple, ):
# Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
# text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
rf,bf,gf = fore_tuple
rb,gb,bb = back_tuple
msg = '{0}' + txt_msg
mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
print(msg .format(mat))
print('\33[0m') # Returns default print color to back to black
# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))
我的两分钱(PyColorTerm):
安装:
sudo apt-get install python-pip
pip install pycolorterm
Python脚本:
from pycolorterm import pycolorterm
with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:
out.write('Works OK!')
“工作正常!”显示为绿色。
对于Windows,除非使用Win32 API,否则无法使用颜色打印到控制台。
对于Linux,它就像使用打印一样简单,转义序列如下:
颜色
要使字符像方框一样打印,这实际上取决于控制台窗口使用的字体。磅符号效果很好,但它取决于字体:
#
import click
click.secho('Hello, World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)
click(CLI库)有一种非常方便的方式来实现这一点,如果您正在编写命令行工具,无论如何都值得考虑。
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行