【发布时间】:2016-02-03 14:19:40
【问题描述】:
我正在尝试使用 Stream.filter() 方法将 twitter 数据流式传输 5 分钟。我将检索到的推文存储在 JSON 文件中。问题是我无法从程序中停止 filter() 方法。我需要手动停止执行。我尝试使用 time 包根据系统时间停止数据。我能够停止将推文写入 JSON 文件,但流方法仍在继续,但无法继续下一行代码。 我正在使用 IPython notebook 来编写和执行代码。 代码如下:
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: Stream data for X minutes?
Stopping Tweepy steam after a duration parameter (# lines, seconds, #Tweets, etc)
Tweepy Streaming - Stop collecting tweets at x amount
我使用这个链接作为我的参考, http://stats.seandolinar.com/collecting-twitter-data-using-a-python-stream-listener/
【问题讨论】:
-
您有一个有效的问题,无需担心。 问题是我无法从程序中停止 filter() 方法是什么意思。您是否要暂停流?或者更改过滤关键字?
-
@Leb 我希望流在需要时运行,比如每小时运行一次。如果我让它永远运行,它只会达到 API 限制并停止工作。我想在代码中以编程方式打开和关闭流。