我尝试使用stream.filter()方法将twitter数据流化5分钟。我将检索到的tweets存储在一个JSON文件中。问题是我无法从程序中停止filter()方法。我需要手动停止执行。我尝试使用时间包根据系统时间停止数据。我可以停止向JSON文件写入tweets,但stream方法仍在继续,但无法继续执行下一行代码。 我正在使用IPython笔记本来编写和执行代码。 代码如下:
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/
访问变量myListener.running,但不要直接将myListener传递给Stream,而是按如下方式创建变量:
要关闭流,需要从
on_data()
或on_status()
返回False
。因为
tweepy.Stream()
本身运行一个while循环,所以在on_data()
中不需要while循环。初始化
MyListener
时,未调用父类的__init__
方法,因此未正确初始化。因此,对于您要做的事情,代码应该如下所示:
所以,我也有这个问题。幸运的是,Tweepy是开源的,所以很容易深入研究这个问题。
最重要的是:
streaming.py中的On Stream类
这意味着,要关闭连接,只需在监听器的on_data()方法上返回false。
相关问题 更多 >
编程相关推荐