2017-03-10 39 views
1

我正在嘗試使用twitter和tweepy的Streaming Api來獲取一些由某些關鍵字(已完成)過濾的推文以及我可以稍後在Google地圖上繪製的座標。然而,當我執行下面的代碼來存儲座標不爲空的那些推文時,我得到一個錯誤。帶座標Tweepy的推文python

代碼:

def on_data(self, data): 

    json_object = json.loads(data) 
    if (json_object["user"]["coordinates"]!="null"): 
     f.write(data) 

一段時間後,我得到的是說

Key error:user

誰能告訴我,爲什麼這個錯誤發生的原因,可以是哪些步驟錯誤採取解決或更好地理解這個錯誤。

回答

2

你會得到這個錯誤,因爲它沒有必要所有的推文將有user字段。

def on_data(self, data): 
    json_object = json.loads(data) 
    # next statement will short circuit if 'user' field is not found. 
    if "user" in json_object and "coordinates" in json_object["user"] and json_object["user"]["coordinates"]!="null": 
     f.write(data) 

或者,如果你想這樣做優雅 -

def on_data(self, data): 
    try: 
     if json_object["user"]["coordinates"]!="null": 
      f.write(data) 
    except: 
     pass 
+0

然後我怎麼可以使程序跳過那些在沒有座標精密組件? – user3930213

+0

@ user3930213我編輯了答案 – hashcode55

+0

您應該知道其他消息類型。 [DOC](https://dev.twitter.com/streaming/overview/messages-types) – Jonas