为什么在上述类中定义TwitterClient时,为什么不断收到93行错误,提示未定义TwitterClient?

时间:2019-04-10 10:22:20

标签: python

这是颤抖的。它说

  

未定义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()

2 个答案:

答案 0 :(得分:0)

这是您的代码的简化版本,可以证明问题所在。

class TwitterClient(object):
    None

    def main():
        api = TwitterClient()
        print("main()")


    if __name__ == "__main__":
        main()

请注意,main()if __name__ == "__main__"的缩进都放在TwitterClient本身的定义下。因此,在Python 3中出现错误:

Traceback (most recent call last):
  File "twitter-55610165.py", line 2, in <module>
    class TwitterClient(object):
  File "twitter-55610165.py", line 11, in TwitterClient
    main()
  File "twitter-55610165.py", line 6, in main
    api = TwitterClient()
NameError: name 'TwitterClient' is not defined
未定义

TwitterClient,因为TwitterClient的类定义尚未完成-您仍在其中。 if在类作用域级别,因此在定义类时运行。缩进关系到Python的范围。

在空格中进行了微小但重要的更改后,将main()if __name__ ...从TwitterClient范围中移出并重新放置到主要范围中,问题就消失了。

class TwitterClient(object):
    None

def main():
    api = TwitterClient()
    print("main()")


if __name__ == "__main__":
    main()

即这些构造现在与TwitterClient处于相同的缩进级别,进一步缩进了一个缩进级别。

$ python3 twitter-55610165.py
main()

答案 1 :(得分:0)

一个简单的解决方案是从main()定义中删除TwitterClient()。 确切的问题是main()TwitterClient()内部内,也就是说,您还没有完成TwitterClient()的定义,因此python会引发错误。

如何修复

最简单的解决方案是从main()定义中移出if __name__...TwitterClient()行。那将摆脱您当前的错误。该代码应该可以工作:

导入     进口tweepy     从tweepy导入OAuthHandler     从textblob导入TextBlob     类TwitterClient(object):         '''        用于情感分析的通用Twitter类。         '''         def init (自己):             '''         类的构造函数或初始化方法。             '''             Twitter开发控制台中的#个键和令牌             Consumer_key ='删除'             Consumer_secret ='移除'             access_token ='删除-删除'             access_token_secret ='删除'

        # 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()