[英]A script in python 2.7 urllib2 and json raises unicode error
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>
。
有人有解決方案嗎?
你要做的可能是解碼而不是編碼響應。
一個非常簡短的解釋為什么http服務器不知道如何發送unicode字符,只是字節。 因此,它使用像utf-8這樣的編碼將這些字符轉換為字節。 當您從服務器收到響應時,您會收到這一塊字節,如果要將其轉換回unicode字符列表(基本上是python中的unicode對象),則必須解碼它們。
更令人困惑的是,使用utf-8時,ascii字符的較低頻譜(codepoint <127)與較低的unicode代碼點完全相同。 這種情況下,unicode代碼點的編碼方式相同,並且適合在每個字符的單個字節中表示的范圍內。
希望這是有幫助的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.