错误 'UnboundLocalError: local variable 'counter' referenced before assignment' 应该怎么解决?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (72)
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程序,扫描所有推文以查找某些单词。直到试图为该单词的实例数添加一个计数器时,所有内容都运行良好。无论我在哪里分配计数器,我总是会得到一个'UnboundLocalError: local variable 'counter' referenced before assignment'错误。我应该在哪里分配这个计划中的计数器?

提问于
用户回答回答于

你还没有分配一个值来计数,方法“on_status”会尝试增加计数器,但只对方法而不是对象本地,因此失败。

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

应该在init方法中初始化计数器,然后使用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)

所属标签

可能回答问题的人

  • 西风

    renzha.net · 站长 (已认证)

    7 粉丝1 提问9 回答
  • 四无君

    0 粉丝0 提问3 回答
  • o o

    3 粉丝491 提问2 回答
  • Dingda

    Dingda · 站长 (已认证)

    4 粉丝0 提问2 回答

扫码关注云+社区

领取腾讯云代金券