【问题标题】:How to recover a Unicode string by its ASCII string in Python?如何通过 Python 中的 ASCII 字符串恢复 Unicode 字符串?
【发布时间】:2020-03-27 15:43:28
【问题描述】:

在提问之前我想先举个例子。

u_string = u'\xcb\xa5\xb5'
u_string
Out[79]: 'Ë¥µ'
asc_string = ascii(u_string)
asc_string
Out[81]: "'\\xcb\\xa5\\xb5'"

到这里,我终于得到了一个只包含ascii字符的ascii字符串(asc_string)。

我的问题是, 如果我只有 asc_string,如何将其转换为原始 u_string(Unicode string)?

谢谢 马丁

【问题讨论】:

  • 如果您不关心安全性,您可以使用 eval()。

标签: python unicode ascii python-unicode


【解决方案1】:

对于这种情况,最简单的完全正确的方法是ast.literal_eval

>>> import ast
>>> origversion = u'\xcb\xa5\xb5'  # Leading u is unnecessary on Python 3
>>> asciiform = ascii(origversion)
>>> origversion == ast.literal_eval(asciiform)
True

之所以有效,是因为在字符串上使用 ascii 会添加引号和转义符以生成包含复制原始字符串的字符串文字的字符串(它只是 repr,但在 repr 中坚持仅使用 ASCII 字符); ast.literal_eval 旨在解析规范的 reprs(ASCII 编码或非 ASCII 编码)以生成结果对象,在本例中为字符串。

【讨论】:

    【解决方案2】:

    你可以这样解码:

    asc_string.encode().decode( 'unicode-escape' )  
    # "'Ë¥µ'"
    

    我不知道为什么,但是 ascii 添加了一组额外的引号,你可以像这样删除那些:

    asc_string.encode().decode( 'unicode-escape' )[1:-1]
    # 'Ë¥µ'
    

    【讨论】:

    • 当字符串没有被引用时,这是一个很好的解决方案,但正如您所注意到的,当您使用 ascii 时,它需要去掉引号(因为ascii 基本上是 "repr,但是是 ASCII 格式,并且 strs 的 reprs 总是被引用)。您还需要显式地将参数传递给 encode'latin-1' (unicode-escape假定 latin-1 编码字节;如果您的语言环境编码不同,某些数据将被损坏)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2011-12-26
    • 2013-04-17
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多