1
import json
import urllib2
url='http://search.twitter.com/search.json?q=python'
open=urllib2.urlopen(url)
response=open.read().encode('utf8')
data=json.loads(response)
results=data['results']
for result in results:
  print result['from_user'] + ': ' + result['text'] + '\n'

给出错误UnicodeEncodeError: 'charmap' codec can't encode characters in position 16-24: character maps to <undefined>

有人对此有解决方案吗?

4

1 回答 1

3

您要做的可能是解码而不是编码响应。

一个非常简短的解释是为什么 http 服务器不知道如何发送 unicode 字符,只是字节。因此,它使用像 utf-8 这样的编码将这些字符转换为字节。当您收到来自服务器的响应时,您会收到此字节块,如果您想将其转换回 unicode 字符列表(基本上是 python 中的unicode对象),则必须对其进行解码。

更令人困惑的是,使用 utf-8 时,较低频谱的 ascii 字符(代码点 < 127)与较低的 unicode 代码点完全相同。一种情况,其中 unicode 代码点既编码相同,又适合每个字符可以用单个字节表示的范围。

希望这会有所帮助。

于 2012-12-07T05:28:31.600 回答