2012-05-11 31 views
0

問候同胞愛好者:爲什麼當我編寫錯誤處理程序忽略unicode之外返回的Unicode錯誤時,使用python從Twitter-api返回範圍之外?

我正在調試與twitter-api集成的程序,其目的是搜索特定半徑的特定推文並將它們返回到csv文件中。它的工作原理....但有時它遇到了「UnicodeEncodeError:'ascii'編解碼器無法編碼字符u'\ u201c'在位置0:序號不在範圍(128)」錯誤,但我調整了我的代碼讓它忽略超出範圍的twitter的Unicode數據。

那麼爲什麼有時候這個錯誤仍然存​​在?

下面是一個在評論中給出的測試輸入運行它的代碼:

import urllib2, json, pprint, codecs, unicodedata, csv 
## test coordinate input: 29.762778,-95.383056 
## test radius 10 
## test query: tebow 
##Initial user input 
city = raw_input("Please enter to 6 decimal places the city\ncoordinates to be searched ex. lat,long: ") 
radius = raw_input("Please enter the numeric value of the\nradius in miles you'd like to search ex. 10: ") 
term= raw_input("Please enter the search term you wish to query ex. tebow: ") 

u = urllib2.urlopen('http://search.twitter.com/search.json?q='+term+'&geocode='+city+','+radius+'mi&page=1&rpp=20') 
datares = json.load(u) 
##pprint.pprint(datares) 

with codecs.open('Geotweets.csv',mode='w', encoding='utf-8',errors='ignore') as cache: 
    writer = csv.writer(cache) 
    for tweet in datares['results']: 
     writer.writerow([tweet['text'], tweet['location'], tweet['created_at'], tweet['from_user']]) 

回答

0

有一個隱藏的轉換在writerow發生。用例如自己對數據進行編碼tweet['text'].encode('ascii', 'ignore')

+0

@Techsan,抱歉 - 您必須開啓另一個問題。 –

+0

@No prob Mark再次感謝! – Techsan

相關問題