python - Getting lat/long coordinates from identified tweets using tweepy; getting KeyError: 'coordinates' -


i'm trying lat/long coordinates identified tweets. part having trouble if decoded['coordinates']!=none: t.write(str(decoded['coordinates']['coordinates']) block. don't know if it's working or not because ~150 tweets returned coordinates [none] before error returned, believe error comes when tweet coordinates found, , returns keyerror: 'coordinates'.

the following code:

import tweepy import json htmlparser import htmlparser import os  consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = ''  # listener, resposible receiving data class stdoutlistener(tweepy.streamlistener):     def on_data(self, data):         # twitter returns data in json format - need decode first         decoded = json.loads(htmlparser().unescape(data))          os.chdir('/home/scott/810py/project')         t = open('hashtaghipster.txt','a')          # also, convert utf-8 ascii ignoring bad characters sent users         #if decoded['coordinates']:          # decoded['coordinates'] returns few objects not useful,         # type , place don't want. ['coordinates'] has         # second thing called ['coordinates'] returns lat/long.         # may code correct location few , far         # between haven't been able capture one. program         # looks 'hipster' in tweet. there should stream of tweets         # in shell , everytime 1 has coordinates tehy should         # added file 'hashtaghipster.txt'. let me know think.          if decoded['coordinates']!=none:             t.write(str(decoded['coordinates']['coordinates'])) #gets [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 new tweets #hipster:"      # there different kinds of streams: public stream, user stream, multi-user streams     # in example follow #vintage tag     # more details refer https://dev.twitter.com/docs/streaming-apis     stream = tweepy.stream(auth, l)     stream.filter(track=['hipster']) 

any help? thanks.

not tweet objects contains 'coordinates' key, have check exists this:

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

also, please note that:

"comparisons singletons none should done 'is' or 'is not', never equality operators."

(pep 8)


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -