使用Tweepy过滤Twitter数据

2024-09-21 03:10:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了marcobonzanini的关于挖掘Twitter数据的教程:https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/

class MyListener(StreamListener):

    def on_data(self, data):
        try:
            with open('python.json', 'a') as f:
                f.write(data)
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True

    def on_error(self, status):
        print(status)
        return True

并使用filter方法的“follow”参数检索此特定ID生成的tweet:

^{pr2}$

但是,它似乎没有完成任务,因为它不仅返回由ID创建的tweets和retweets,而且还返回提到ID的每个tweet(即retweets)。那不是我想要的。在

我确信一定有办法做到这一点,因为Twitter给出的json文件中有一个“screen_name”字段。screen\u name字段给出了Tweet创建者的名称。我只需要找到如何过滤屏幕上的数据。在


Tags: 数据selfidjsontruedatareturnon
1条回答
网友
1楼 · 发布于 2024-09-21 03:10:14

就是这样设计的。引用Twitter streaming API docs

For each user specified, the stream will contain:

  • Tweets created by the user.
  • Tweets which are retweeted by the user.
  • Replies to any Tweet created by the user.
  • Retweets of any Tweet created by the user.
  • Manual replies, created without pressing a reply button (e.g. “@twitterapi I agree”).

对于您来说,处理它的最佳方法是在收到tweet时检查是谁创建的,我相信可以按照以下方法进行:

class MyListener(StreamListener):
    def on_data(self, data):
        try:
            if data._json['user']['id'] == "63728193":
                with open('python.json', 'a') as f:
                    f.write(data)
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True

    def on_error(self, status):
        print(status)
        return True

相关问题 更多 >

    热门问题