我有一个工作脚本可以成功收集提到“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/