2012-03-10 96 views
0

有很多關於解析twitter json的帖子,但沒有人看到我解決了我的問題。使用json python解析unicoded tweet

這是代碼

import json 

file = open('tweet', 'r') 
tweet = file.read() 
#{"geo":null,"text":"Lmao!! what time? I dont finish evening cleaning till 5 RT \[email protected]_user: football anyone?.....i wanna have a kickabout :(\u201d"} 
#{"geo":null,"text":"Lmao!! what time? I dont finish evening cleaning till 5 RT @some_user: football anyone?.....i wanna have a kickabout :("} 
def parseStreamingTweet(tweet): 
    try: 
     singleTweetJson = json.loads(tweet) 
     for index in singleTweetJson: 
      if index == 'text': 
       print "text : ", singleTweetJson[index] 
    except ValueError: 
     print "Error ", tweet 
     print ValueError 
     return 

parseStreamingTweet(tweet) 

這是測試程序。鳴叫流入和檢查目的,我已經保存在文件中的推文,並檢查。有一個twitter feed的編輯部分。

任何人都可以說我如何解析單向編碼的推文。評論中的第一條推文是uni編碼,第二條不是。首先出現錯誤,同時刪除uni-code字符串,解析成功。什麼是解決方案?

回答

2

我認爲你的代碼有效,錯誤的原因可能是因爲你嘗試向終端打印unicode值時發生UnicodeEncodeError。我猜你是在一個不支持unicode的終端中調用腳本。相反,如果你打印的Unicode值的再版,或(就寫了一個輸出文件),它可能會工作:

print "text : ", repr(singleTweetJson[index]) 

而且它通常是不好的做法,以隱藏與通用catch-特定的異常/錯誤信息所有異常/錯誤消息。

+0

謝謝!這工作!但我打印在unicode支持的終端(我正在使用Netbeans IDE,並且支持unicode),並且消息打印在異常中,但不在數組'文本'中,反正它工作!謝謝! – Curiousity 2012-03-10 16:15:39