[英]How to convert string containing unicode escape \u#### to utf-8 string
我从早上开始就在尝试这个。
我的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逸出字符串的文本文件(我确切不知道它的名字)并将其转换为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 = 選択'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.