2017-08-25 304 views
2

我只学了很短时间的Python,所以我通过其他人的例子来练习。我想在Twitter上进行文字过滤,其Python代码可以总结如下。对象没有属性'count'

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' 

我觉得我的版本和我的版本是不正确的,因为我已经修改了一些部分。

我该怎么办?

+0

限定self.count = 0类__init__()方法 – Kallz

回答

1
self.count += 1 

蟒蛇把它读作

self.count = self.count + 1 

那搜索self.count第一再加入+ 1,并分配给self.count。

- =,* =,/ =对于减法,乘法和除法是类似的。

What += exactly do ??

在你的代码,你不初始化self.count。初始化计数定义__init_ self.count()类的方法

def __init__(self) 
    self.count = 0 
+0

@RachelPark很高兴帮助内,如果这答案解决了您的问题,请点击答案旁边的复选标记将其标记为已接受。见:接受答案如何工作? https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Kallz

+0

我检查了答案旁边的标记,是吗?因为我第一次使用这个计算器.. –

+0

@RachelPark是的,接受解决你的问题的答案是正确的。 ::) – Kallz

0

这是因为你没有初始化计数变量无论是在用户定义的类CustomStreamListener()主要程序。

可以在主程序初始化它,并将它传递到类以这样的方式:

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