from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
from pprint import pprint
data_file = open('twitter.json')
data = json.load(data_file)
##Json file with all the ckey, csecret, atoken, and asecret
pprint(data)
#consumer key, consumer secret, access token, access secret.
ckey = data["ckey"]
csecret = data["csecret"]
atoken = data["atoken"]
asecret = data["asecret"]
class listener(StreamListener):
def on_data(self, data):
all_data = json.loads(data)
tweet = all_data["text"]
username = all_data["user"]["screen_name"]
print((username,tweet))
return True
def on_error(self, status):
print (status)
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
上面的代码是访问 twitter api 的所有标准。但是,我需要将从 twitter 获得的推文传输到 .txt 文件中。我尝试使用下面的代码 twitterStream = Stream(auth, listener())
fid = open("cats based tweets.txt","w")
for tweet in twitterStream.filter(track=[cats]):
fid.write(tweet)
fid.close()
我打算找到所有包含关键字猫的推特推文/转发,确实如此。但是,它还应该编写一个包含所有推文的 txt 文件,但它没有。谁能告诉我我需要做什么来修复它。
编辑:我使用了你们编写的代码,但它没有返回所有推文。它像 5 或 6 一样打印出来,然后是错误
RuntimeError: No active exception to reraise
出现,我不知道为什么。为什么会发生这种情况,因为我知道它不应该。