gpt4 book ai didi

python - 如何更有效地为文本着色?

转载 作者:行者123 更新时间:2023-12-04 01:03:53 26 4
gpt4 key购买 nike

所以我知道如何为文本着色,我使用一个类来定义颜色,然后在打印语句中使用它 -

class color:
purple = '\033[95m'
cyan = '\033[96m'
darkcyan = '\033[36m'
blue = '\033[94m'
green = '\033[92m'
yellow = '\033[93m'
end = '\033[0m'

print(color.green + This makes the text green! + color.end)
但我正在为 CSE 类(class)做一个项目,有很多文本要阅读,最终所有的白色都融合在一起,所以使用彩色文本会让事情变得更容易,所以我想知道是否有一种更简单、更省时的方法做事的?

最佳答案

您可以实现自己的函数来接受文本和颜色、插入必要的代码并进行打印。如果你想使用一个类,就像你在做的那样,我建议子类化 Enum , 并以全部大写的形式命名颜色本身,这是 Python 的常量约定。 (另外,如果你以前没有看过 f 弦,我推荐 giving them a look 。)

from enum import Enum

class Color(Enum):
PUPLE = 95
CYAN = 96
DARK_CYAN = 36
BLUE = 94
GREEN = 92
YELLOW = 93
# (Add any further colors you want to use...)

def color_print(text, color):
"""Print text in the specified color."""
if color not in Color:
raise KeyError(f'Invalid text color: {color}')

print(f'\033[{color.value}m{text}\033[0m')
您可以像这样使用:
color_print('This text should be blue.', Color.BLUE)
你也可以用字典完成同样的事情。我不确定一种方法是否比另一种更好或更干净,因此您可以选择对您来说更好的阅读方式,并且看起来使用起来更方便。
COLORS = {
'purple': 95,
'cyan': 96,
'dark_cyan': 36,
'blue': 94,
'green': 92,
'yellow': 93,
# (Add any further colors you want to use...)
}

def color_print(text, color):
"""Print text in the specified color."""
try:
code = COLORS[color]
except KeyError:
raise KeyError(f'Invalid text color: {color}')

print(f'\033[{code}m{text}\033[0m')
对于这种方法,您将颜色指定为字符串而不是枚举的成员:
color_print('This text should be blue.', 'blue')
还有一个名为 ansi-colors 的包看起来它有很多有用的选项(例如设置前景色和背景色,并检查颜色编码字符串的“实际”长度而不计算转义码)。它自 2017 年以来一直没有更新,但可能值得一试。

关于python - 如何更有效地为文本着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67154948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com