微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何更有效地为文本着色?

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

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 课程做一个项目,有很多文本要阅读,最终所有的白色都融合在一起,所以使用彩色文本会让事情变得更容易,所以我想知道是否有更简单、更短的时间消费,做事方式?

解决方法

您可以实现自己的函数,接受文本和颜色、插入必要的代码并打印。如果你想使用一个类,就像你正在做的那样,我建议子类化 Enum,并将颜色本身命名为全部大写,这是 Python 的常量约定。 (另外,如果您之前没有看过 f-strings,我建议您使用 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 年以来就没有更新过,但可能值得一试。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。