我是Python的新手,正在尝试使用Tweepy和流API从Twitter检索数据并将其转换为CSV文件的应用程序。
问题在于这段代码没有创建输出CSV文件,可能是因为我应该设置代码在达到例如1000个推文时停止,但我不知道如何设置停止点。
以下是代码:
import sys
import tweepy
import csv
#pass security information to variables
consumer_key=""
consumer_secret=""
access_key = ""
access_secret = ""
#use variables to access twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
#create an object called 'customStreamListener'
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
print (status.author.screen_name, status.created_at, status.text)
def on_error(self, status_code):
print >> sys.stderr, 'Encountered error with status code:', status_code
return True # Don't kill the stream
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream
streamingAPI = tweepy.streaming.Stream(auth, CustomStreamListener())
streamingAPI.filter(track=['Dallas', 'NewYork'])
def on_status(self, status):
with open('OutputStreaming.txt', 'w') as f:
f.write('Author,Date,Text')
writer = csv.writer(f)
writer.writerow([status.author.screen_name, status.created_at, status.text])
有什么建议吗?
on_status
函数不在CustomStreamListener
类中。 - Selcuk