2017-08-25 331 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