我只學了很短時間的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'
我覺得我的版本和我的版本是不正確的,因爲我已經修改了一些部分。
我該怎麼辦?
限定self.count = 0類__init__()方法 – Kallz