【发布时间】:2016-02-01 18:44:34
【问题描述】:
在解析 HTML 响应以在 Bash CLI 中的 Kubuntu 15.10 上使用 Python 3.4 提取数据时,使用 print() 我得到如下所示的输出:
\u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
如何在我的应用程序中输出实际文本本身?
这是生成字符串的代码:
response = requests.get(url)
messages = json.loads( extract_json(response.text) )
for k,v in messages.items():
for message in v['foo']['bar']:
print("\nFoobar: %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('\n'):
if 'foobar' in line:
return line[line.find('"')+1:-2].replace(r'\"',r'"')
return None
在谷歌搜索该问题时,我发现information 中的quite a bit 与Python 2 相关,但是Python 3 完全改变了Python 中处理字符串的方式,尤其是Unicode。 p>
如何在 Python 3 中将示例字符串 (\u05ea) 转换为字符 (ת)?
附录:
这里有一些关于message['body']的信息:
print(type(message['body']))
# Prints: <class 'str'>
print(message['body'])
# Prints: \u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
print(repr(message['body']))
# Prints: '\\u05ea\u05d4 \\u05e0\\u05e9\\u05de\\u05e2 \\u05de\\u05e6\\u05d5\\u05d9\\u05df'
print(message['body'].encode().decode())
# Prints: \u05ea\u05d4 \u05e0\u05e9\u05de\u05e2 \u05de\u05e6\u05d5\u05d9\u05df
print(message['body'].encode().decode('unicode-escape'))
# Prints: תה נשמע מצוין
请注意,最后一行确实按预期工作,但存在一些问题:
- 使用 unicode-escape 解码字符串文字是错误的,因为 Python 转义不同于 JSON 转义的许多字符。 (谢谢bobince)
-
encode()依赖默认编码,这是一件坏事。(谢谢bobince) -
encode()在某些较新的 Unicode 字符(例如 \ud83d\ude03)上失败,并出现 UnicodeEncodeError “surrogates not allowed”。
【问题讨论】:
-
什么是
print(ascii(message['body']))?无关:使用messages = response.json()。 -
如果输入不是 JSON 那么它是什么?
print(response.content[:50]);print(response.headers['Content-Type'])。可以更改服务返回的上游格式吗? -
这不是我问的。按原样运行注释中的代码。
-
@J.F.Sebastian:
b'\r\n\n\n<!DOCTYPE html> <html lang="en"> <head> <meta '和text/html; charset=utf-8。谢谢。 -
现在我们正在取得进展。您能否发布用于获取
messages的真实代码? (在requests.get()和json.loads()之间,包括)
标签: python python-3.x string unicode python-3.4