unicode在python2上是如何工作的?我就是不明白。
在这里,我从服务器下载数据并将其解析为JSON。
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/eventlet-0.9.12-py2.6.egg/eventlet/hubs/poll.py", line 92, in wait
readers.get(fileno, noop).cb(fileno)
File "/usr/local/lib/python2.6/dist-packages/eventlet-0.9.12-py2.6.egg/eventlet/greenthread.py", line 202, in main
result = function(*args, **kwargs)
File "android_suggest.py", line 60, in fetch
suggestions = suggest(chars)
File "android_suggest.py", line 28, in suggest
return [i['s'] for i in json.loads(opener.open('https://market.android.com/suggest/SuggRequest?json=1&query='+s+'&hl=de&gl=DE').read())]
File "/usr/lib/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.6/json/decoder.py", line 336, in raw_decode
obj, end = self._scanner.iterscan(s, **kw).next()
File "/usr/lib/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/usr/lib/python2.6/json/decoder.py", line 217, in JSONArray
value, end = iterscan(s, idx=end, context=context).next()
File "/usr/lib/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/usr/lib/python2.6/json/decoder.py", line 183, in JSONObject
value, end = iterscan(s, idx=end, context=context).next()
File "/usr/lib/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/usr/lib/python2.6/json/decoder.py", line 155, in JSONString
return scanstring(match.string, match.end(), encoding, strict)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data
谢谢你!!
编辑:以下字符串导致错误:'[{"t":"q","s":"abh\xf6ren"}]'
。应将\xf6
解码为ö
(abhören)
发布于 2011-06-01 00:16:25
您试图解析为JSON的字符串不是以UTF-8编码的。它很可能是以ISO-8859-1编码的。尝试以下操作:
json.loads(unicode(opener.open(...), "ISO-8859-1"))
它将处理可能出现在JSON消息中的任何变音。
你应该读一下乔尔·斯波尔斯基的The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)。我希望它能澄清你在Unicode方面遇到的一些问题。
发布于 2012-06-11 14:06:40
我的解决方案有点有趣。我从来没有想过它会像使用UTF-8编解码器一样容易保存。我使用的是notepad++(5.6.8版).I最初没有注意到我用ANSI编解码器保存它。我使用单独的文件来放置所有本地化的字典。我在我的Notepad++.I的“编码”选项卡下找到了我的解决方案,选择“不带BOM的UTF-8编码”并保存它。它工作得很好。
发布于 2013-08-22 07:16:13
将编码更改为Latin1 /ISO8859-1的解决方案解决了我在tex4ht的输出上调用html2text.py时观察到的一个问题。我将其用于自动统计LaTeX文档的字数: tex4ht将其转换为HTML语言,然后html2text.py将其剥离为纯文本,以便通过wc -w进行进一步统计。现在,例如,如果一个德语"Umlaut“通过文献数据库条目进入,那么这个过程将失败,因为html2text.py会抱怨例如。
UnicodeDecodeError:'utf8‘编解码器无法解码位置32243-32245中的字节:无效数据
现在,这些错误随后将特别难以追踪,基本上您希望在您的参考资料部分中有Umlaut。html2text.py内部的一个简单更改,来自
data =data.decode(编码)
至
数据= data.decode("ISO-8859-1")
解决了这个问题;如果您使用HTML文件作为第一个参数来调用脚本,那么您也可以将编码作为第二个参数传递,而不必进行修改。
https://stackoverflow.com/questions/6180521
复制相似问题