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

问题描述

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

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 年以来就没有更新过,但可能值得一试。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...