gpt4 book ai didi

python - Tweepy Streaming - 停止收集 x 数量的推文

转载 作者:太空狗 更新时间:2023-10-30 00:40:53 24 4
gpt4 key购买 nike

在我在 MongoDB 中存储了 x # 条推文后,我希望让 Tweepy Streaming API 停止拉入推文。

我在类中尝试了 IF 和 WHILE 语句,用计数器定义,但无法让它在某个 X 数量处停止。这对我来说是一个真正的头脑 Storm 。我在这里找到了这个链接:https://groups.google.com/forum/#!topic/tweepy/5IGlu2Qiug4但是我复制它的努力失败了。它总是告诉我 init 需要一个额外的参数。我相信我们的 Tweepy 身份验证设置不同,所以这不是同类。

有什么想法吗?

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json, time, sys

import tweepy
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

class StdOutListener(StreamListener):

def on_status(self, status):
text = status.text
created = status.created_at
record = {'Text': text, 'Created At': created}
print record #See Tweepy documentation to learn how to access other fields
collection.insert(record)


def on_error(self, status):
print 'Error on status', status

def on_limit(self, status):
print 'Limit threshold exceeded', status

def on_timeout(self, status):
print 'Stream disconnected; continuing...'


stream = Stream(auth, StdOutListener())
stream.filter(track=['tv'])

最佳答案

您需要在 __init__ 中的类中添加一个计数器,然后在 on_status 中递增它。然后,当计数器低于 20 时,它将向集合中插入一条记录。这可以如下所示完成:

def __init__(self, api=None):
super(StdOutListener, self).__init__()
self.num_tweets = 0

def on_status(self, status):
record = {'Text': status.text, 'Created At': status.created_at}
print record #See Tweepy documentation to learn how to access other fields
self.num_tweets += 1
if self.num_tweets < 20:
collection.insert(record)
return True
else:
return False

关于python - Tweepy Streaming - 停止收集 x 数量的推文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20863486/

24 4 0