如何将包含Unicode转义\ u ####的字符串转换为utf-8字符串
问题内容:
我从早上开始就在尝试这个。
我的 sample.txt
choice = \u9078\u629e
码:
with open('sample.txt', encoding='utf-8') as f:
for line in f:
print(line)
print("選択" in line)
print(line.encode('utf-8').decode('utf-8'))
print(line.encode().decode('utf-8'))
print(line.encode('utf-8').decode())
print(line.encode().decode('unicode-escape').encode("latin-1").decode('utf-8')) # as suggested.
out:
choice = \u9078\u629e
False
choice = \u9078\u629e
choice = \u9078\u629e
choice = \u9078\u629e
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 9-10: ordinal not in range(256)
当我在ipython qtconsole中执行此操作时:
In [29]: "choice = \u9078\u629e"
Out[29]: 'choice = 選択'
因此,问题是如何读取包含Unicode逸出字符串的文本文件\u9078\u629e
(例如,我确切不知道它叫什么)并将其转换为utf-8 選択
?
问题答案:
如果您从文件中读取它,只需在打开时提供编码:
with open('test.txt', encoding='unicode-escape') as f:
a = f.read()
print(a)
# choice = 選択
用test.txt
含有:
选择= \ u9078 \ u629e
如果您已经在字符串中输入了文本,则可以这样进行转换:
a = "choice = \\u9078\\u629e"
a.encode().decode('unicode-escape')
# 'choice = 選択'