如何在Python终端显示扑克牌Unicode符号?读取文件时为何无法显示?
解决Python终端无法正确显示扑克牌Unicode符号的问题
问题说明
从数据文件读取扑克牌的Unicode转义字符串后,即使移除多余反斜杠,终端仍无法显示对应的扑克牌符号;但直接在代码中定义的Unicode符号却能正常渲染。
代码与文件内容
原代码
import re file = open("arrayOfCards",'r') while True: next_line = file.readline() if not next_line: break; d = next_line.split(',') print(re.sub(r'\'','',d[2])) file.close() card = ['A','diamonds','\U0001F0C1','14'] print(type(card[2]), card[2])
数据文件arrayOfCards内容
A,diamonds,\U0001F0C1,14 A,clubs,\\U0001F0D1,14
实际输出
\U0001F0C1 \\U0001F0D1 <class 'str'> 🃁
解决方案
问题核心:从文件读取的是转义序列的字符串字面量,Python不会自动将其解析为对应的Unicode字符;而代码中直接定义的\U0001F0C1会被解释器直接转换成Unicode字符。
以下是两种可行的转换方法:
方法1:使用ast.literal_eval
利用ast模块的literal_eval函数安全解析转义字符串,将其转换为实际Unicode字符:
import re import ast with open("arrayOfCards",'r') as file: for next_line in file: if not next_line.strip(): continue d = next_line.split(',') raw_str = re.sub(r'\'','',d[2]).strip() unicode_char = ast.literal_eval(f'"{raw_str}"') print(unicode_char) card = ['A','diamonds','\U0001F0C1','14'] print(type(card[2]), card[2])
方法2:使用unicode_escape解码
通过编码+解码的方式,将转义字符串转换为Unicode字符:
import re with open("arrayOfCards",'r') as file: for next_line in file: if not next_line.strip(): continue d = next_line.split(',') raw_str = re.sub(r'\'','',d[2]).strip() unicode_char = raw_str.encode('utf-8').decode('unicode_escape') print(unicode_char) card = ['A','diamonds','\U0001F0C1','14'] print(type(card[2]), card[2])
额外提示
- 推荐使用
with语句管理文件,避免手动关闭文件时可能出现的资源泄漏问题。 - 处理每行内容时调用
strip(),可以去除换行符、首尾空格,避免影响转义序列的解析。
内容的提问来源于stack exchange,提问作者Роман Городилов
相关产品推荐
相关产品推荐

