Skip to main content
 首页 » 编程设计

python之对象没有属性 'count'

2025年02月15日7JustinYoung

我学习 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 。初始化计数在类的 __init_() 方法中定义 self.count

def __init__(self) 
    self.count = 0