如何将unicode转换为unicode转义的文本

谬误的推理

我正在加载带有一堆unicode字符(例如\xe9\x87\x8b)的文件。我想\u91cb在Python中将这些字符转换为它们的转义unicode形式()。我在StackOverflow上发现了几个类似的问题,包括在Python3的字符串中评估UTF-8文字转义序列的过程,它几乎完全符合我的要求,但我无法解决如何保存数据的问题。

例如:输入文件:

\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

虚假的

您需要使用编码再次对其进行unicode-escape编码。

>>> br'\xe9\x87\x8b'.decode('unicode-escape').encode('latin1').decode('utf-8')
'釋'
>>> _.encode('unicode-escape')
b'\\u91cb'

修改代码(使用二进制模式以减少不必要的编码/解码)

with open("input.txt", "rb") as f:
    text = f.read().rstrip()  # rstrip to remove trailing spaces
decoded = text.decode('unicode-escape').encode('latin1').decode('utf-8')
with open("output.txt", "wb") as f:
    f.write(decoded.encode('unicode-escape'))

http://asciinema.org/a/797ruy4u5gd1vsv8pplzlb6kq

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章