对象没有属性'count'



我只学了很短的时间Python,所以我正在通过其他人的例子来练习。我想在Twitter上做单词过滤,它的Python代码可以总结如下。

import tweepy
import simplejson as json
from imp import reload
import sys
reload(sys)
consumer_key = 'blah'
consumer_skey = 'blah'
access_tokenA = 'blah'
access_stoken = 'blah'
def get_api():
api_key = consumer_key
api_secret = consumer_skey
access_token = access_tokenA
access_token_secret = access_stoken
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_token_secret)
return auth
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
print ('Got a Tweet')
self.count += 1
tweet = status.text
tweet = self.pattern.sub(' ',tweet)
words = tweet.split()
for word in words:
if len(word) > 2 and word != '' and word not in self.common:
if word not in self.all_words:
self.all_words[word] = 1
else:
self.all_words[word] += 1
if __name__ == '__main__':
l = CustomStreamListener()
try:
auth = get_api()
s = "obamacare"
twitterStreaming = tweepy.Stream(auth, l)
twitterStreaming.filter(track=[s])
except KeyboardInterrupt:
print ('-----total tweets-----')
print (l.count)
json_data = json.dumps(l.all_words, indent=4)
with open('word_data.json','w') as f:
print >> f, json_data
print (s)

但是有一个错误如下。

File "C:/Users/ID500/Desktop/Sentiment analysis/untitled1.py", line 33, in on_status
self.count += 1
AttributeError: 'CustomStreamListener' object has no attribute 'count'

我认为示例的版本和我的版本不正确,因为我已经修改了一些部分。

我该怎么办?

self.count += 1

Python 将其读作

self.count = self.count + 1

首先搜索 self.count,然后添加 + 1 并分配给 self.count。

-=, *=,/= 对减法、乘法和除法执行类似的操作。

+=到底做了什么??

在您的代码中,您没有初始化 self.count 。 要初始化计数,请在类的__init_((方法中定义self.count

def __init__(self)
self.count = 0

这是因为您尚未在用户定义的类CustomStreamListener((程序中初始化 count 变量。

您可以在主程序中初始化它,并通过以下方式将其传递给类:

count=<some value>
class CustomStreamListener(tweepy.StreamListener):
def __init__(self,count):
self.count=count
def on_status(self, status):
print ('Got a Tweet')
self.count += 1
tweet = status.text
tweet = self.pattern.sub(' ',tweet)
words = tweet.split()
for word in words:
if len(word) > 2 and word != '' and word not in self.common:
if word not in self.all_words:
self.all_words[word] = 1
else:
self.all_words[word] += 1

最新更新