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

时间:2015-09-15 04:36:33

标签: python python-3.x unicode

我正在加载带有一堆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

3 个答案:

答案 0 :(得分:3)

您需要使用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

答案 1 :(得分:1)

\xe9\x87\x8b不是Unicode字符。它看起来像是一个字节串的表示,表示使用utf-8字符编码编码的 Unicode字符。 \u91cb是Python源代码(或JSON格式)中字符的表示。不要混淆文本表示和角色本身:

>>> b"\xe9\x87\x8b".decode('utf-8')
u'\u91cb' # repr()
>>> print(b"\xe9\x87\x8b".decode('utf-8'))
釋
>>> import unicodedata
>>> unicodedata.name(b"\xe9\x87\x8b".decode('utf-8'))
'CJK UNIFIED IDEOGRAPH-91CB'

要从文件中读取编码为utf-8的文本,请明确指定字符编码:

with open('input.txt', encoding='utf-8') as file:
    unicode_text = file.read()

将Unicode文本保存到文件完全相同:

with open('output.txt', 'w', encoding='utf-8') as file:
    file.write(unicode_text)

如果省略显式encoding参数,则使用locale.getpreferredencoding(False),如果它与用于保存文件的实际字符编码不对应,则可能产生mojibake。

如果您的输入文件字面上包含\xe9(4个字符),那么您应该修复生成它的任何软件。如果您需要使用'unicode-escape';有些东西坏了。

答案 2 :(得分:0)

看起来您的输入文件是UTF-8编码的,因此在打开文件时指定UTF-8编码(根据您的参考假定Python3):

with open("input.txt", "r", encoding='utf8') as f:
    text = f.read()

text将包含文件内容为str(即unicode字符串)。现在,您可以通过指定encoding='unicode-escape'

将它以unicode转义形式直接写入文件
with open('output.txt', 'w', encoding='unicode-escape') as f:
    f.write(text)

您文件的内容现在将包含unicode-escaped literals:

$ cat output.txt
\u91cb
相关问题