简体   繁体   中英

Tweets with Coordinates Tweepy python

I am trying to use Streaming Api of twitter and tweepy to get some tweets filtered by some keywords(already done) and their coordinates which I can later plot on google map. However i am getting an error when I am executing the following code to store only those tweets where coordinates are not null.

Code:

def on_data(self, data):

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

After some time I get an error that says

Key error:user

Can anybody tell me the reason why this error happened and what steps can be taken to resolve or understand this error better.

You are getting this error because its not necessary all the tweets will have the user field.

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)

Or if you want to do this gracefully -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM