如何在Python中将彩色文本输出到终端?
当前回答
耶!另一个版本
虽然我觉得这个答案很有用,但我做了一些修改。此GitHub Gist是结果
用法
print colors.draw("i'm yellow", bold=True, fg_yellow=True)
此外,还可以包装常用用法:
print colors.error('sorry, ')
https://gist.github.com/Jossef/0ee20314577925b4027f
其他回答
如果您正在使用Django:
>>> from django.utils.termcolors import colorize
>>> print colorize("Hello, World!", fg="blue", bg='red',
... opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)
快照:
(我通常在runserver终端上使用彩色输出进行调试,所以我添加了它。)
您可以测试它是否安装在您的机器中:$python-c“import django;print django.VERSION”。要安装它,请查看:如何安装django
试试看!!
另一个包装Python3打印功能的PyPI模块:
https://pypi.python.org/pypi/colorprint
如果您也可以从__future_import-print中使用,它可以在Python2.x中使用。下面是模块PyPI页面中的Python 2示例:
from __future__ import print_function
from colorprint import *
print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])
它输出“你好,世界!”,单词为蓝色,感叹号为粗体红色并闪烁。
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库)有一种非常方便的方式来实现这一点,如果您正在编写命令行工具,无论如何都值得考虑。
这里有一个本机适用于Windows 10的解决方案。
使用系统调用,如os.system(“”),允许在命令提示符和Powershell中以本机方式打印颜色:
import os
# System call
os.system("")
# Class of different styles
class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
print(style.YELLOW + "Hello, World!")
注意:Windows不完全支持ANSI代码,无论是通过系统调用还是模块。并非所有的文字装饰都受支持,虽然显示的是明亮的颜色,但它们与常规颜色相同。
感谢@j-l找到了更短的方法。
tl;dr:添加os.system(“”)
这个答案试图通过使用正则表达式为文本块中的关键字着色来扩展将着色文本写入终端的概念。
这个答案还使用了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输出