python - 如何将 tweepy Twitter 流保存到文件中?

标签 python twitter tweepy

我有一个工作脚本可以成功收集提到“stackoverflow”的推文。但是,我想在 iPython 中运行脚本(而不是执行一个单独的 .py 文件)。理想情况下,我只想打开它的 ipyb 文件,选择全部运行,让它运行一周左右(当然不是关闭我的笔记本电脑),结果我有一个 .json 文件,其中包含一周的推文。

这是我目前所拥有的:

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener

access_token = "x"
access_token_secret = "x"
consumer_key = "x"
consumer_secret = "x"

# file name that you want to open is the second argument
save_file = open('data.json', 'a')

class listener(StreamListener):

    def on_data(self, data):
        print(data)
        return True

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

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["stackoverflow"])

最佳答案

将以下代码添加到您现有的代码中。 'fetched_tweets.txt' 是您要保存以 'a'(追加模式)打开的推文的文件名。

class StdOutListener(StreamListener):

    def on_data(self, data):
        #print data
        with open('fetched_tweets.txt','a') as tf:
            tf.write(data)
        return True

    def on_error(self, status):
        print status

关于python - 如何将 tweepy Twitter 流保存到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28130124/

相关文章:

python - 在python中并排绘制两个图像

python - 使用 Tweepy 编写通知程序

python - 如何使用 Python/flask 将 Twitter 元数据从服务器流式传输到客户端浏览器

python - 用户 ID 到用户名 tweepy

python - 为什么我的 Python 机器人有时会发布过多的帖子?

python - 我想在 Flask 中制作漂亮的 JSON 格式

python - 如何编写一个函数来接受 SWIG 中的 Fraction 对象?

python - 如何将行转置为 Pandas 中的列?

ios - 从 UITableViewCell 分配变量以在主视图 Controller 中发送推文

algorithm - twitter 之类的应用程序是如何实现的?