【问题标题】:Limit tweepy stream to a specific number将 tweepy 流限制为特定数字
【发布时间】:2015-08-23 15:40:00
【问题描述】:
class listener(StreamListener):

def on_status(self, status):
    try:
        userid = status.user.id_str
        geo = str(status.coordinates)
        if geo != "None":
            print(userid + ',' + geo)
        else:
            print("No coordinates")
        return True
    except BaseException as e:
        print('failed on_status,',str(e))
        time.sleep(5)

def on_error(self, status):
    print(status)


auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)

twitterStream = Stream(auth, listener())
twitterStream.filter(locations=[-97.54,32.55,-97.03,33.04])

我的 tweepy 流有这个脚本,它运行良好。但是,它会一直运行,直到我使用 'ctrl+c' 终止它。我尝试向“on_status”添加一个计数器,但它不会增加:

 class listener(StreamListener):

def on_status(self, status):
    i = 0
    while i < 10:
        userid = status.user.id_str
        geo = str(status.coordinates)
        if geo != "None":
            print(userid + ',' + geo)
            i += 1

无论我把增量放在哪里,它都会重复。如果我在课程前添加“i=0”,我会收到错误:

RuntimeError: No active exception to reraise

知道如何使计数器与流媒体一起使用吗?至少据我所知,tweepy 附带的光标不适用于流式传输。

【问题讨论】:

    标签: python python-3.x twitter tweepy twitter-streaming-api


    【解决方案1】:

    您的 while 逻辑无法正常工作,因为 Tweepy 在收到数据时会在内部调用 on_status() 方法。因此,您无法通过在已经运行的无限循环中引入条件来控制流程,最好的方法是在类中创建一个新变量,该变量在创建 listener 对象时被实例化。并在 on_data() 方法中增加该变量。

    class listener(StreamListener):
    
        def __init__(self):
            super().__init__()
            self.counter = 0
            self.limit = 10
    
        def on_status(self, status):
            try:
                userid = status.user.id_str
                geo = str(status.coordinates)
                if geo != "None":
                    print(userid + ',' + geo)
                else:
                    print("No coordinates")
                self.counter += 1
                if self.counter < self.limit:
                    return True
                else:
                    twitterStream.disconnect()
            except BaseException as e:
                print('failed on_status,',str(e))
                time.sleep(5)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 2021-01-16
    • 2018-03-25
    • 1970-01-01
    • 2020-04-03
    • 2020-06-09
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多