【问题标题】:How to convert %uXXXX code to plain text in python?如何在 python 中将 %uXXXX 代码转换为纯文本?
【发布时间】:2019-09-19 07:05:00
【问题描述】:

我有像 '%u0E1E%u0E1A%u0E40%u0E08%u0E2D%u0E02%u0E27%u0E14%u0E40' 这样的字符串,我想将其转换为纯文本 'พบเจอ' 我尝试使用函数 ord() 和 chr() 作为 follwos

chr(ord(u'\u0E1E')) 将给出回文文本。

split_list = encoded_string.split('%')
for i in range(1,len(split_list)):
    split_list[i]= '\\'+split_list[i]
split_list
['', '\\u0E1E', '\\u0E1A', '\\u0E40', '\\u0E08', '\\u0E2D', '\\u0E02', '\\u0E27', '\\u0E14',.....]

现在当我使用以下循环将其转换为纯文本时

for i in range(1,len(split_list)):
    split_list[i] = chr(ord(u''+split_list[i]))

出现以下错误

TypeError                                 Traceback (most recent call last)
<ipython-input-104-5ab6fb196276> in <module>
      1 for i in range(1,len(split_list)):
----> 2     split_list[i] = chr(ord(u''+split_list[i]))

TypeError: ord() expected a character, but string of length 6 found

请帮我解决这个问题提前谢谢。

【问题讨论】:

    标签: python unicode character-encoding


    【解决方案1】:

    您似乎有一个字符串,其中通常用于表示非 ascii 字符的反斜杠表示已被基于百分号的约定替换。

    解决方案是用反斜杠替换百分号 - 正如您所尝试的那样 - 然后编码为字节并从 unicode-escape 编解码器解码。结果将是 Python str

    >>> s = '%u0E1E%u0E1A%u0E40%u0E08%u0E2D%u0E02%u0E27%u0E14%u0E40'
    >>> # Encode to latin-1 as it won't lose any information.
    >>> result = s.replace('%', '\\').encode('latin-1').decode('unicode-escape')
    >>> result
    'พบเจอขวดเ'
    >>> # Result is longer than we expected
    >>> expected = 'พบเจอ' 
    >>> result == expected
    False
    >>> expected in result
    True
    >>> result.startswith(expected)
    True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 2020-03-06
      • 2011-02-09
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      相关资源
      最近更新 更多