Python:dictionary值的八进制转义字符\033在print语句中转换为UTF-8字符

2024-05-19 03:13:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我在terminal和Python2.7.3中尝试了一些颜色输出。ANSI颜色代码总是在终端中完美地呈现出来,除了这一个小的例外,我还不能精确地指出任何比这个特定的字典定义更精确的地方。

以下是造成混乱的原因:

color = {
    'white':    "\033[1,37m",
    'yellow':   "\033[1,33m",
    'green':    "\033[1,32m",
    'blue':     "\033[1,34m",
    'cyan':     "\033[1,36m",
    'red':      "\033[1,31m",
    'magenta':  "\033[1,35m",
    'black':    "\033[1,30m",
    'darkwhite':  "\033[0,37m",
    'darkyellow': "\033[0,33m",
    'darkgreen':  "\033[0,32m",
    'darkblue':   "\033[0,34m",
    'darkcyan':   "\033[0,36m",
    'darkred':    "\033[0,31m",
    'darkmagenta':"\033[0,35m",
    'darkblack':  "\033[0,30m",
    'off':        "\033[0,0m"
}

yellow = "\033[1;33m"
off = "\033[0;0m"

print color['yellow'] + "string to render" + color['off']     # fails to render properly
print "%(yellow)sstring to render%(off)s" % color             # ditto
print "%sstring to render%s" % (color['yellow'], color['off'])# ditto

print yellow + "string to render" + off                       # as intended

pp = pprint.PrettyPrinter(indent=6)
pp.pprint(color)

预打印输出:

{ 'black': '\x1b[1,30m',
  'blue': '\x1b[1,34m',
  'cyan': '\x1b[1,36m',
  'darkblack': '\x1b[0,30m',
  'darkblue': '\x1b[0,34m',
  'darkcyan': '\x1b[0,36m',
  'darkgreen': '\x1b[0,32m',
  'darkmagenta': '\x1b[0,35m',
  'darkred': '\x1b[0,31m',
  'darkwhite': '\x1b[0,37m',
  'darkyellow': '\x1b[0,33m',
  'green': '\x1b[1,32m',
  'magenta': '\x1b[1,35m',
  'off': '\x1b[0,0m',
  'red': '\x1b[1,31m',
  'white': '\x1b[1,37m',
  'yellow': '\x1b[1,33m'}

在我看来,这是十六进制格式的正确翻译。尽管如此,字典值并没有正确地传递给print语句。raw和Unicode(出于绝望)字符串文本修饰符都不会改变任何内容。我一定错过了一些很明显的东西。在不支持UTF-8的终端上,将省略Unicode字符。

我见过 termcolor

if os.getenv('ANSI_COLORS_DISABLED') is None:
    fmt_str = '\033[%dm%s'
    if color is not None:
        text = fmt_str % (COLORS[color], text)

    if on_color is not None:
        text = fmt_str % (HIGHLIGHTS[on_color], text)

    if attrs is not None:
        for attr in attrs:
            text = fmt_str % (ATTRIBUTES[attr], text)

    text += RESET
return text

colorama

CSI = '\033['
def code_to_chars(code):
    return CSI + str(code) + 'm'
class AnsiCodes(object):
    def __init__(self, codes):
        for name in dir(codes):
            if not name.startswith('_'):
                value = getattr(codes, name)
                setattr(self, name, code_to_chars(value))

还有其他几个。从分析上讲,它们都避免在字典中定义整个序列。我同意这种方法在词汇上是合理的。然而,事实仍然是,从字典值中的转义字符不能正确解释,除了在perl散列、C++的{{CD1}}化^ ^ },或者C的^ {< CD3}}(如果是一个映射)^ {CD4}}。

这就引出了一个问题:根据标准,如果可能的话,是否有一个特别的原因,解释为什么字典(让我们称之为this:)插值偏离普通字符串?


这里是固定的颜色代码dict(如果编辑,则缩进制表符,因此似乎要删除制表符以供读取):

color = {
    'white':    "\033[1;37m",
    'yellow':   "\033[1;33m",
    'green':    "\033[1;32m",
    'blue':     "\033[1;34m",
    'cyan':     "\033[1;36m",
    'red':      "\033[1;31m",
    'magenta':  "\033[1;35m",
    'black':      "\033[1;30m",
    'darkwhite':  "\033[0;37m",
    'darkyellow': "\033[0;33m",
    'darkgreen':  "\033[0;32m",
    'darkblue':   "\033[0;34m",
    'darkcyan':   "\033[0;36m",
    'darkred':    "\033[0;31m",
    'darkmagenta':"\033[0;35m",
    'darkblack':  "\033[0;30m",
    'off':        "\033[0;0m"
}

Tags: totextnoneif字典isnotcode
1条回答
网友
1楼 · 发布于 2024-05-19 03:13:28

我看过你的源代码,我想问题出在字典里的颜色定义上了。

如果仔细观察,颜色的字典值类似于白色。但是应该是\033[1;30m。请注意,您使用的是“,(逗号)字符,而不是“;(分号)字符。作为测试,我创建了颜色字典的一个子集并运行了这些测试。

>>> color = {'white' :'\033[1;37m', 'yellow':'\033[1;33m', 'off' : '\033[0;0m'}
>>> print color['white'] + 'string' + color['off']
string   #this string is white in color
>>> print color['yellow'] + 'string' + color['off']
string #this string is yellow in color
>>> color['yellow'] = '\033[1,33m' #incorrect color code - using a , character instead of ;
>>> print color['yellow'] + 'string' + color['off']
string   #prints the string in console default color i.e. not in yellow color
>>> 

希望这有帮助

相关问题 更多 >

    热门问题