我正在加载一个包含许多unicode字符的文件(例如
\xe9\x87\x8b
)。我想在Python中将这些字符转换为其转义的unicode形式(\u91cb
)。我在StackOverflow上找到了几个类似的问题,包括这个Evaluate UTF-8 literal escape sequences in a string in Python3,它几乎完全符合我的要求,但我不知道如何保存数据。
例如: 输入文件:
\xe9\x87\x8b
Python脚本:
file = open("input.txt", "r")
text = file.read()
file.close()
encoded = text.encode().decode('unicode-escape').encode('latin1').decode('utf-8')
file = open("output.txt", "w")
file.write(encoded) # fails with a unicode exception
file.close()
期望的输出文件:
\u91cb
print(open('input.txt', 'rb').read())
是什么?它是b'\xe9\x87\x8b'
还是b'\\xe9\\x87\\x8b'
? - jfs