python - 为什么我一直收到第 93 行错误,说 TwitterClient 在上面的类中定义时未定义?
问题描述
这是给 tweepy 的。它说
TwitterClient 未定义。
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
class TwitterClient(object):
'''
Generic Twitter Class for sentiment analysis.
'''
def __init__(self):
'''
Class constructor or initialization method.
'''
# keys and tokens from the Twitter Dev Console
consumer_key = 'remove'
consumer_secret = 'remove'
access_token = 'remove-remove'
access_token_secret = 'remove'
# attempt authentication
try:
# create OAuthHandler object
self.auth = OAuthHandler(consumer_key, consumer_secret)
# set access token and secret
self.auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
self.api = tweepy.API(self.auth)
except:
print("Error: Authentication Failed")
def clean_tweet(self, tweet):
'''
Utility function to clean tweet text by removing links, special characters
using simple regex statements.
'''
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
def get_tweet_sentiment(self, tweet):
'''
Utility function to classify sentiment of passed tweet
using textblob's sentiment method
'''
# create TextBlob object of passed tweet text
analysis = TextBlob(self.clean_tweet(tweet))
# set sentiment
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'
def get_tweets(self, query, count = 10):
'''
Main function to fetch tweets and parse them.
'''
# empty list to store parsed tweets
tweets = []
try:
# call twitter api to fetch tweets
fetched_tweets = self.api.search(q = query, count = count)
# parsing tweets one by one
for tweet in fetched_tweets:
# empty dictionary to store required params of a tweet
parsed_tweet = {}
# saving text of tweet
parsed_tweet['text'] = tweet.text
# saving sentiment of tweet
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
# appending parsed tweet to tweets list
if tweet.retweet_count > 0:
# if tweet has retweets, ensure that it is appended only once
if parsed_tweet not in tweets:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)
# return parsed tweets
return tweets
except tweepy.TweepError as e:
#print error (if any)
print("Error : " + str(e))
def main():
#creating object of TwitterClient Class
api = TwitterClient()
#calling function to get tweets
tweets = api.get_tweets(query = 'ADF', count = 200)
#picking positive tweets from tweets
ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
# percentage of positive tweets
print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
#picking negative tweets from tweets
ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
#percentage of negative tweets
print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
#percentage of neutral tweets \
netweets = [tweet for tweet in tweets if tweet['sentiment'] == 'neutral']
print("Neutral tweets percentage: {} %".format(100*(len(netweets)/len(tweets))))
#printing first 5 positive tweets
print("\n\nPositive tweets:")
for tweet in ptweets[:10]:
print(tweet['text'])
#printing first 5 negative tweets
print("\n\nNegative tweets:")
for tweet in ntweets[:10]:
print(tweet['text'])
if __name__ == "__main__":
#calling main function
main()
解决方案
一个简单的解决方案是main()
从TwitterClient()
定义中删除。确切的问题是main()
在里面,TwitterClient()
换句话说你还没有完成定义TwitterClient()
,所以python抛出错误。
怎么修
最简单的解决方案是从定义中移动main()
和if __name__...
行。TwitterClient()
这将摆脱您当前的错误。此代码应该可以工作:
import re import tweepy from tweepy import OAuthHandler from textblob import TextBlob class TwitterClient(object): ''' 用于情绪分析的通用 Twitter 类。''' def init (self): ''' 类构造函数或初始化方法。''' # 来自 Twitter 开发控制台的密钥和令牌 consumer_key = 'remove' consumer_secret = 'remove' access_token = 'remove-remove' access_token_secret = 'remove'
# attempt authentication
try:
# create OAuthHandler object
self.auth = OAuthHandler(consumer_key, consumer_secret)
# set access token and secret
self.auth.set_access_token(access_token, access_token_secret)
# create tweepy API object to fetch tweets
self.api = tweepy.API(self.auth)
except:
print("Error: Authentication Failed")
def clean_tweet(self, tweet):
'''
Utility function to clean tweet text by removing links, special characters
using simple regex statements.
'''
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
def get_tweet_sentiment(self, tweet):
'''
Utility function to classify sentiment of passed tweet
using textblob's sentiment method
'''
# create TextBlob object of passed tweet text
analysis = TextBlob(self.clean_tweet(tweet))
# set sentiment
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'
def get_tweets(self, query, count = 10):
'''
Main function to fetch tweets and parse them.
'''
# empty list to store parsed tweets
tweets = []
try:
# call twitter api to fetch tweets
fetched_tweets = self.api.search(q = query, count = count)
# parsing tweets one by one
for tweet in fetched_tweets:
# empty dictionary to store required params of a tweet
parsed_tweet = {}
# saving text of tweet
parsed_tweet['text'] = tweet.text
# saving sentiment of tweet
parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)
# appending parsed tweet to tweets list
if tweet.retweet_count > 0:
# if tweet has retweets, ensure that it is appended only once
if parsed_tweet not in tweets:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)
# return parsed tweets
return tweets
except tweepy.TweepError as e:
#print error (if any)
print("Error : " + str(e))
def main():
#creating object of TwitterClient Class
api = TwitterClient()
#calling function to get tweets
tweets = api.get_tweets(query = 'ADF', count = 200)
#picking positive tweets from tweets
ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
#percentage of positive tweets
print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
#picking negative tweets from tweets
ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
#percentage of negative tweets
print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
#percentage of neutral tweets \
netweets = [tweet for tweet in tweets if tweet['sentiment'] == 'neutral']
print("Neutral tweets percentage: {} %".format(100*(len(netweets)/len(tweets))))
#printing first 5 positive tweets
print("\n\nPositive tweets:")
for tweet in ptweets[:10]:
print(tweet['text'])
#printing first 5 negative tweets
print("\n\nNegative tweets:")
for tweet in ntweets[:10]:
print(tweet['text'])
if __name__ == "__main__":
#calling main function
main()
推荐阅读
- javascript - Vue js组件在没有页面刷新的情况下不渲染数据
- android - 无法使用 GSON 解析空白 JSON 字符串
- julia - 修改代码以改进模拟
- android - Wifi 直接连接在 Raspberry Pi 中几秒钟后自动断开连接
- android - 如何将 32 位 .so 文件转换为 64 位 .so 文件用于 android
- java - 我想在 Jframe 中添加带或不带 DB 值的 Dynamic Swing 组件?
- c - 暂停破壳
- angular - 如何使用spring boot后端使角度应用程序仅接收来自局域网的请求?
- python - python - 如何在python中为矩阵或二维数组的每个元素设置特定条件?
- android - 尝试访问该方法时出错,因为“没有@Provides-annotated 方法就无法提供”