按照事情的方式,我在 python 中解码一些 unicode 时遇到问题
具体来说,这个网页:xkcd.com/403/info.0.json
相关部分是Paul Erd\u00c5\u0091s!
当我通过 json 解码器运行它时,unicode 被解码,但没有使用正确的编解码器
我目前正在使用单行:
requests.get("http://xkcd.com/403/info.0.json").json()["alt"][-12:]
得到'Paul ErdÅ\x91s!'
这显然不是我想要的
有什么想法可以解决这个问题吗?
最佳答案
要修复该 JSON,您需要编码为 Latin-1(因为它会天真地转码字节),然后从 UTF-8 解码。
两次。因为它是双断的。
>>> json.loads('"Erd\u00c3\u0085\u00c2\u0091s!"')
u'Erd\xc3\x85\xc2\x91s!'
>>> json.loads('"Erd\u00c3\u0085\u00c2\u0091s!"').encode('latin-1').decode('utf-8')
u'Erd\xc5\x91s!'
>>> json.loads('"Erd\u00c3\u0085\u00c2\u0091s!"').encode('latin-1').decode('utf-8').encode('latin-1').decode('utf-8')
u'Erd\u0151s!'
>>> print json.loads('"Erd\u00c3\u0085\u00c2\u0091s!"').encode('latin-1').decode('utf-8').encode('latin-1').decode('utf-8')
Erdős!
关于python - json 网页的 Unicode 解码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24876817/