在Python3中将Unicode序列转换为字符串转换为、字符串、中将、序列

2023-09-04 02:07:14 作者:醉月拂人泪乄

在Bash CLI中使用Python3.4在Kubuntu 15.10上使用print()解析HTML响应以提取数据时,我得到的输出如下所示:

u05eau05d4 u05e0u05e9u05deu05e2 u05deu05e6u05d5u05d9u05df

如何在应用程序中输出实际文本本身?

python字符串和编码 ascii unicode utf 8 gb231

这是生成字符串的代码:

response = requests.get(url)
messages = json.loads( extract_json(response.text) )

for k,v in messages.items():
    for message in v['foo']['bar']:
        print("
Foobar: %s" % (message['body'],))

下面是从HTML页面返回JSON的函数:

def extract_json(input_):

    """
    Get the JSON out of a webpage.
    The line of interest looks like this:
    foobar = ["{"name":"dotan","age":38}"]
    """

    for line in input_.split('
'):
        if 'foobar' in line:
            return line[line.find('"')+1:-2].replace(r'"',r'"')

    return None

在谷歌搜索该问题时,我发现information的Python 2与Python 2相关,但是Python3已经完全改变了在Python中处理字符串的方式,尤其是Unicode。

如何在Python3中将示例字符串(u05ea)转换为字符(ת)?

附录:

以下是有关message['body']的一些信息:

print(type(message['body']))
# Prints: <class 'str'>

print(message['body'])
# Prints: u05eau05d4 u05e0u05e9u05deu05e2 u05deu05e6u05d5u05d9u05df

print(repr(message['body']))
# Prints: '\u05eau05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df'

print(message['body'].encode().decode())
# Prints: u05eau05d4 u05e0u05e9u05deu05e2 u05deu05e6u05d5u05d9u05df

print(message['body'].encode().decode('unicode-escape'))
# Prints: תה נשמע מצוין

请注意,最后一行确实可以正常工作,但它有几个问题:

使用unicode转义来解码字符串文字是错误的,因为对于许多字符来说,Python转义与JSON转义是不同的。(谢谢bobince) encode()依赖默认编码,这是不好的。(谢谢bobince) encode()在某些较新的Unicode字符上失败,例如ud83dude03,UnicodeEncodeError"不允许代理"。

推荐答案

您的输入似乎使用了反斜杠作为转义字符,您应该在将文本传递给json之前对其进行反转义:

>>> foobar = '{\"body\": \"\\u05e9\"}'
>>> import re
>>> json_text = re.sub(r'\(.)', r'1', foobar) # unescape
>>> import json
>>> print(json.loads(json_text)['body'])
ש

不要对JSON文本使用'unicode-escape'编码;它可能会产生不同的结果:

>>> import json
>>> json_text = '["\ud83d\ude02"]'
>>> json.loads(json_text)
['']
>>> json_text.encode('ascii', 'strict').decode('unicode-escape') #XXX don't do it
'["ud83dude02"]'

'' == 'U0001F602'为U+1F602 (FACE WITH TEARS OF JOY)。