python - 无法让计数器在 tweepy 中工作
问题描述
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:分配前引用的局部变量”计数器“错误。在这个程序中我应该在哪里分配计数器?
解决方案
假设上面的“不能”实际上不在您的代码中,如果可能,请更新您的问题以省略“'”,因为它会破坏可读性或更改为其他一些占位符文本。
如错误所示,您尚未为计数器分配值,方法“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)
推荐阅读
- rxjs - 为什么共享运算符不阻止可观察到的触发两次?
- javascript - 如何按数据区域选择元素
- flutter - 单独隔离内的 Firestore 侦听器
- tcpdump - ssldump 出现错误“错误:长度不匹配”
- javascript - OperLayers:在获取标记时显示标记
- batch-file - 如何创建将打开 .bat 文件的 .inf 文件
- vue.js - promisify filereader.onload 在 vue 中得到 TypeError: Cannot read property 'then' of undefined"
- python - 尝试仅根据变量的值更改 tkinter 标签的颜色
- cryptography - 如何解决指数为 65537 的 rsa 相关消息攻击?
- netlogo - netlogo realistic predator behaviour