2015-04-29 62 views
0

我試圖從已識別的推文中獲取緯度/經度座標。我遇到的部分是if decoded['coordinates']!=None: t.write(str(decoded['coordinates']['coordinates'])塊。我不知道它是否正常工作,因爲有時~150推文會在返回錯誤之前以座標[None]的形式返回,所以我相信當找到帶有座標的推文時,錯誤會再次出現,然後返回KeyError: 'coordinates'使用tweepy從已識別的推文獲取緯度/經度座標;獲取KeyError:'座標'

下面是我的代碼:

import tweepy 
import json 
from HTMLParser import HTMLParser 
import os 

consumer_key = '' 
consumer_secret = '' 
access_token = '' 
access_token_secret = '' 

# This is the listener, resposible for receiving data 
class StdOutListener(tweepy.StreamListener): 
    def on_data(self, data): 
     # Twitter returns data in JSON format - we need to decode it first 
     decoded = json.loads(HTMLParser().unescape(data)) 

     os.chdir('/home/scott/810py/Project') 
     t = open('hashtagHipster.txt','a') 

     # Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users 
     #if decoded['coordinates']: 

     # decoded['coordinates'] returns a few objects that are not useful, 
     # like type and place which we don't want. ['coordinates'] has a 
     # second thing called ['coordinates'] that returns just the lat/long. 
     # it may be that the code is correct but location is so few and far 
     # between that I haven't been able to capture one. This program just 
     # looks for 'hipster' in the tweet. There should be a stream of tweets 
     # in the shell and everytime one that has coordinates tehy should be 
     # added to the file 'hashtagHipster.txt'. Let me know what you think. 

     if decoded['coordinates']!=None: 
      t.write(str(decoded['coordinates']['coordinates'])) #gets just [LAT][LONG] 
     print '[%s] @%s: %s' % (decoded['coordinates'], decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore')) 
     print '' 
     return True 

    def on_error(self, status): 

     print status 

if __name__ == '__main__': 
    l = StdOutListener() 
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
    auth.set_access_token(access_token, access_token_secret) 

    print "Showing all new tweets for #hipster:" 

    # There are different kinds of streams: public stream, user stream, multi-user streams 
    # In this example follow #vintage tag 
    # For more details refer to https://dev.twitter.com/docs/streaming-apis 
    stream = tweepy.Stream(auth, l) 
    stream.filter(track=['hipster']) 

任何幫助嗎?謝謝。

+0

't.write(str(decoded ['coordinates'] ['coordinates']))'看起來很奇怪。你打算在那裏寫兩次「座標」嗎? – Kevin

+0

是的。 decode ['coordinates']返回json和python的混合,它看起來像{'type':'「,'place':」「,'coordinates':[-123.45667],[123.235667]}, 'coordinates'] ['coordinates']只返回[-123.45667],[123.235667]。 – triscuit312

+0

當然,最簡單的做法是在't.print ...'行之前打印'coded ['coordinates']'的內容。從回溯看來,它看起來沒有關鍵的「座標」。 – SiHa

回答

2

並非所有的鳴叫對象包含「座標」鍵,所以你要檢查它像這樣的東西存在:

if decoded.get('coordinates',None) is not None: 
    coordinates = decoded.get('coordinates','').get('coordinates','') 

另外,請注意:

"Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators."

PEP 8

+0

所以,你認爲我可以把它放在那裏,如果阻塞,然後添加第三行,說t.write(座標)的東西? – triscuit312