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

Par*_*døx 3 python console escaping ansi-colors

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

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)
Run Code Online (Sandbox Code Playgroud)

但我正在为 CSE 课程做一个项目,需要阅读很多文本,最终所有白色都会混合在一起,所以使用彩色文本会让事情变得更容易,所以我想知道是否有一种更简单、更省时的方法做事的?

Cra*_*cky 6

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

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')
Run Code Online (Sandbox Code Playgroud)

你可以这样使用:

color_print('This text should be blue.', Color.BLUE)
Run Code Online (Sandbox Code Playgroud)

您也可以使用字典完成同样的事情。我不确定一种方法是否比另一种更好或更干净,因此您可以选择对您来说更好并且似乎使用起来更方便的方法。

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')
Run Code Online (Sandbox Code Playgroud)

对于这种方法,您可以将颜色指定为字符串而不是枚举的成员:

color_print('This text should be blue.', 'blue')
Run Code Online (Sandbox Code Playgroud)

如果您想要现成的解决方案,还有Rich软件包。它具有一系列令人印象深刻的功能,包括但当然不限于以指定颜色进行打印。复制上述内容的最简单方法可能如下所示:

from rich.console import Console

console = Console()
console.print('This text shoudl be blue', style="blue")
Run Code Online (Sandbox Code Playgroud)

Rich 还可以执行一些操作,例如换行和对齐文本、设置前景色和背景色、使文本闪烁、包含表情符号,以及(在我看来,这可能是有用的)智能地对数据输出进行颜色编码,并在终端中突出显示语法。我自己刚刚发现了这个库,我建议您看一下。