![](/img/trans.png)
[英]How do I get powershell or windows terminal to print color text using ansi escape codes?
[英]How do I get python to interpret the ANSI escape codes for colors in a string read from a text file
我尝试过的所有代码都可以在 VS Code 终端和 Widows 终端(电源脚本和命令窗口)中运行,所以我对此感到非常高兴,但是,当我从文本文件中读取字符串并打印字符串时,转义码以普通视图打印,并且没有颜色应用于字符串。
我已经尝试过八进制、十六进制和 unicode 版本,我遇到了与“\n”相同的问题,直到我意识到读取的字符串将包含“\n”,它会有效地转义“”字符,所以调用.replace字符串上的 ("\\n","\n") 解决了这个问题,但我对颜色代码并不满意。
这是我用来读取文件的代码:
with open('ascii_art_with_color.txt','r') as file:
for line in file.readlines() :
text_line = line
print( text_line , end='' )
来自 ascii 文件的示例:
encounter = You \033[31mencounter\033[0m a wolf howling at the moonlight
使用 print function 打印效果很好,无论是字符串常量还是来自变量
print('The wolf \033[31mgrowls\033[0m at you as you try to get closer')
winning = 'The wolf lets out a \033[34mpiercing\033[0m cry, then falls to the ground'
print(winning)
想法? 让我难过的主要问题是代码没有被解释/应用于我从文本文件中读取的字符串,其他任何东西似乎都有效。
更新:
正如评论中所建议的那样,该文件包含“\033”(4 个字符)而不是“\033”一个字符。 我希望 python 会占用这条线,然后在打印时将其应用/翻译/编码为 ANSI 转义序列代码,就像上面示例中的字符串一样。
与此同时,我设法使用用转义序列替换特定字符串的脚本来获取文本文件中的颜色(我猜 python 在将其写入文件之前在幕后进行编码)
file_dest = 'ascii_monster_wolf_dest.txt'
with open(file_name,'r') as file, open(file_dest,'w+') as file_dest:
for line in file.readlines():
line = line.replace('{@}','\033[31m')
line = line.replace('{*}','\033[0m')
file_dest.writelines(line)
这是一些进步,但不是我真正想要的。
回到我的问题,有没有办法读取文件并将序列 '\033'(4 个字符)解释为 1 字符转义序列,这似乎与字符串一样?
有几种方法可以按照您的要求进行操作。
如果您用引号将各个行括起来,使它们看起来像 Python 字符串常量,您可以使用 ast 文字评估器对其进行解码:
s = '"\\x61\\x62"'
# That string has 10 characters.
print( ast.literal_eval(s) )
# Prints ab
或者,您可以将字符串转换为字节字符串,并使用“unicode-escape”编解码器:
s = '\\x61\\x62'
s = s.encode('utf-8').decode('unicode-escape')
print( s )
# Prints ab
然而,以我的拙见,使用其他类型的标记来表示您的 colors 会更好。 我的意思是这样的:
<red>This is red</red> <blue>This is blue</blue
也许不完全是 HTML 类型的语法,而是带有您理解的代码标记的东西,可以被人类阅读,并且可以被所有语言解释。
以二进制格式打开文件。 然后按照 Tim Roberts 的建议使用 decode() 。
with open('ascii_art_with_color.txt','rb') as file:
for line in file.readlines() :
print( line.decode('unicode-escape') , end='' )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.