简体   繁体   English

与坐标Tweepy python的推文

[英]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. 我正在尝试使用Twitter和tweepy的Streaming Api来获取由某些关键字(已经完成)及其坐标过滤的某些推文,以后可以在Google地图上进行绘制。 However i am getting an error when I am executing the following code to store only those tweets where coordinates are not null. 但是,当我执行以下代码以仅存储坐标不为null的那些tweet时,出现错误。

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. 您正在收到此错误,因为并非所有推文都将具有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)

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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