我正在尝试使用Stream.filter()方法,流式传输Twitter数据,持续时间为5分钟。我将获取的推文存储在JSON文件中。问题是,我无法在程序内停止filter()方法的执行。我需要手动停止执行。我尝试使用time包基于系统时间停止数据传输。我能够停止写入推文到JSON文件,但stream方法仍在进行中,它无法继续执行下一行代码。我使用IPython笔记本编写和执行代码。以下是代码:
这些链接类似,但都没有直接回答我的问题。
- Tweepy: 如何在 X 分钟内获取流数据? - 如何在设定的持续时间(行数、秒数、推文数等)后停止 Tweepy 流? - Tweepy Streaming - 如何在达到一定数量时停止收集推文? 我参考了这个链接:http://stats.seandolinar.com/collecting-twitter-data-using-a-python-stream-listener/
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
from tweepy import Stream
from tweepy.streaming import StreamListener
class MyListener(StreamListener):
def __init__(self, start_time, time_limit=60):
self.time = start_time
self.limit = time_limit
def on_data(self, data):
while (time.time() - self.time) < self.limit:
try:
saveFile = open('abcd.json', 'a')
saveFile.write(data)
saveFile.write('\n')
saveFile.close()
return True
except BaseException as e:
print 'failed ondata,', str(e)
time.sleep(5)
return True
def on_status(self, status):
if (time.time() - self.time) >= self.limit:
print 'time is over'
return false
def on_error(self, status):
if (time.time() - self.time) >= self.limit:
print 'time is over'
return false
else:
print(status)
return True
start_time = time.time()
stream_data = Stream(auth, MyListener(start_time,20))
stream_data.filter(track=['name1','name2',...list ...,'name n'])#list of the strings I want to track
这些链接类似,但都没有直接回答我的问题。
- Tweepy: 如何在 X 分钟内获取流数据? - 如何在设定的持续时间(行数、秒数、推文数等)后停止 Tweepy 流? - Tweepy Streaming - 如何在达到一定数量时停止收集推文? 我参考了这个链接:http://stats.seandolinar.com/collecting-twitter-data-using-a-python-stream-listener/