对象没有属性 'count'

Object has no attribute 'count'

我学习Python的时间很短,所以我正在通过其他人的例子进行练习。我想在推特上做词过滤,它的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。

-=, *=, /= 做减法、乘法和除法类似。

What += exactly do ??

在您的代码中,您没有初始化 self.count 。在 class

的 __init_() 方法中初始化计数定义 self.count
def __init__(self)
    self.count = 0

这是因为您没有在用户定义的 class CustomStreamListener()main[= 中初始化计数变量17=] 程序。

您可以在主程序中对其进行初始化,然后以这种方式将其传递给class:

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