首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在tweepy中无法使用计数器

在tweepy中无法使用计数器
EN

Stack Overflow用户
提问于 2018-06-02 04:04:54
回答 1查看 167关注 0票数 0
from tweepy import OAuthHandler

import tweepy
from tweepy import StreamListener
from tweepy import Stream


import time



consumer_key = 'super secret consumer key'
consumer_secret = 'shhhhh can't tell anyone this!'
access_token = 'hmmmmmmmmmmmmm'
access_secret = 'arrays should start at 0'

auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)
print('')
print('starting...')
time.sleep(3)

class MySteamListener(tweepy.StreamListener):







    def on_status(self, status):
        #prints status text. can be replaced with a counter probably.
        counter = counter + 1
        print(status.text)


    def on_error(self, status_code):
        if status_code == 420:
            print('420 error')
            #Ends stream in case of rate limiting
            return False


mySteamListener = MySteamListener()

myStream = tweepy.Stream(auth = api.auth, listener = mySteamListener)

myStream.filter(track = ['Warriors'])

我是tweepy的新手,我要做的第一件事就是编写一个程序,扫描所有tweet中的特定单词。在我尝试为该单词添加一个实例数计数器之前,一切都运行得很好。无论我在哪里赋值计数器,我总是得到一个'UnboundLocalError: local variable ' counter‘赋值前引用’错误。在这个程序中我应该把计数器分配到哪里?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-02 04:20:46

假设上面的“不能”并不在你的代码中,如果可能的话,更新你的问题以省略"'“,因为它弄乱了可读性或更改为其他占位符文本。

如错误所示,您还没有为计数器赋值,方法"on_status“将尝试递增计数器,但这只是该方法的本地计数器,而不是对象,因此它失败了。

def on_status(self, status):
        #prints status text. can be replaced with a counter probably.
        counter = counter + 1
        print(status.text)

您应该在初始化方法中初始化计数器,然后改用self.counter。

添加

...
class MySteamListener(tweepy.StreamListener):

    def __init__(self):
        # Not sure if necessary, to make this work, but you could
        # Initialize the inherited class as well (this may work only in Python 3)
        # super().__init__()
        self.counter = 0
...

将on_status修改为

def on_status(self, status):
        #prints status text. can be replaced with a counter probably.
        self.counter = self.counter + 1
        # Can be written as 'self.counter += 1'
        print(status.text)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50650345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档