对象没有属性'count'

时间:2017-08-25 05:18:06

标签: python api twitter tweepy

我只在短时间内学习过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'

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

我该怎么办?

2 个答案:

答案 0 :(得分:1)

self.count += 1

python将其读作

self.count = self.count + 1

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

- =,* =,/ =与减法,乘法和除法相似。

What += exactly do ??

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

的__init_()方法中定义self.count
def __init__(self)
    self.count = 0

答案 1 :(得分:0)

这是因为您尚未在用户定义的类 CustomStreamListener() main 程序中初始化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