如何在Python中将彩色文本输出到终端?
当前回答
为了解决这个问题,我创建了一个简单得让人麻木的程序包,用插值颜色代码打印字符串,称为icolor。
icolor包含两个函数:cformat和cprint,每个函数都包含一个字符串和子字符串,这些子字符串被插值以映射到ANSI转义序列。
from icolor import cformat # there is also cprint
cformat("This is #RED;a red string, partially with a #xBLUE;blue background")
'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m'
包括所有ANSI颜色(例如#RED;、#BLUE;等)以及#RESET#粗体;以及其他。
背景色具有x前缀,因此绿色背景将为#xGREEN;。
一个人可以用##逃脱#。
鉴于其简单性,最好的文档可能是代码本身。
它在PYPI上,因此可以使用sudo easy_install icolor。
其他回答
根据乔尔德的回答,这简直太简单了:
class PrintInColor:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
END = '\033[0m'
@classmethod
def red(cls, s, **kwargs):
print(cls.RED + s + cls.END, **kwargs)
@classmethod
def green(cls, s, **kwargs):
print(cls.GREEN + s + cls.END, **kwargs)
@classmethod
def yellow(cls, s, **kwargs):
print(cls.YELLOW + s + cls.END, **kwargs)
@classmethod
def lightPurple(cls, s, **kwargs):
print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)
@classmethod
def purple(cls, s, **kwargs):
print(cls.PURPLE + s + cls.END, **kwargs)
那么就
PrintInColor.red('hello', end=' ')
PrintInColor.green('world')
这个答案试图通过使用正则表达式为文本块中的关键字着色来扩展将着色文本写入终端的概念。
这个答案还使用了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输出
您可以使用Clint:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
def black(text):
print('\033[30m', text, '\033[0m', sep='')
def red(text):
print('\033[31m', text, '\033[0m', sep='')
def green(text):
print('\033[32m', text, '\033[0m', sep='')
def yellow(text):
print('\033[33m', text, '\033[0m', sep='')
def blue(text):
print('\033[34m', text, '\033[0m', sep='')
def magenta(text):
print('\033[35m', text, '\033[0m', sep='')
def cyan(text):
print('\033[36m', text, '\033[0m', sep='')
def gray(text):
print('\033[90m', text, '\033[0m', sep='')
black("BLACK")
red("RED")
green("GREEN")
yellow("YELLOW")
blue("BLACK")
magenta("MAGENTA")
cyan("CYAN")
gray("GRAY")
联机尝试
如果你正在编程一个游戏,也许你想改变背景颜色,只使用空格?例如:
print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"
推荐文章
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列
- 熊猫在每组中获得最高的n个记录
- 熊猫数据帧得到每组的第一行