基于Python twitter的感伤分析

时间:2018-02-02 21:18:13

标签: python twitter sentiment-analysis

这是我在基于推特的情绪数据分析中得到的错误 在主要

  

tweets = api.Get_tweets(query ='Dengue',count = 200)AttributeError:   “TwitterClient”对象没有属性“Get_tweets”>>>

def get_tweets(self, query, count = 10):
            tweets = []
    try:



        fetched_tweets = self.api.search(q = query, count = count)


        for tweet in fetched_tweets:
                            parsed_tweet = {}


            parsed_tweet['text'] = tweet.text

            parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)


            if tweet.retweet_count > 0:

                if parsed_tweet not in tweets:
                    tweets.append(parsed_tweet)
            else:
                tweets.append(parsed_tweet)


        return tweets

    except tweepy.TweepError as e:

        print("Error : " + str(e))

def main():

api = TwitterClient()

tweets = api.get_tweets(query = 'Dengue', count = 200)

2 个答案:

答案 0 :(得分:0)

查看您正在使用的缩进,get_tweets似乎不是TwitterClient的成员。

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

class TwitterClient:
    api = tweepy.API(auth)
    def get_tweets(self, query, count = 10):
        tweets = []
        try:
            fetched_tweets = self.api.search(q = query, count = count)

            for tweet in fetched_tweets:
                parsed_tweet = {}
                parsed_tweet['text'] = tweet.text
                parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)

                if tweet.retweet_count > 0:
                    if parsed_tweet not in tweets:
                        tweets.append(parsed_tweet)
                else:
                    tweets.append(parsed_tweet)

            return tweets

        except tweepy.TweepError as e:
            print("Error : " + str(e))

def main():
    client = TwitterClient()
    tweets = client.get_tweets(query = 'Dengue', count = 200)

main()

此代码可确保get_tweetsTwitterClient的成员。另请注意,我考虑使用api的约定,将main()中的client重命名为self.api,这可能不那么令人困惑。

答案 1 :(得分:0)

导入重新 导入tweepy

来自tweepy导入OAuthHandler

从textblob导入TextBlob

来自Twitter导入Twitter

类TwitterClient(对象):     '''

用于情绪分析的通用Twitter类。     '''

def init (自我):         '''

Class constructor or initialization method.
    '''

    # keys and tokens from the Twitter Dev Console

CONSUMER_KEY =''

CONSUMER_SECRET =''

=的access_token''

access_token_secret =''

    # attempt authentication

尝试:

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

除了:

        print("Error: Authentication Failed")

def clean_tweet(self,tweet):

    '''

    Utility function to clean tweet text by removing links, special
使用简单的正则表达式语句

字符。

    '''

返回' ' .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'

类TwitterClient:

api = tweepy.API(auth)

def get_tweets(self, query, count = 10):

    tweets = []

    try:

        fetched_tweets = self.api.search(q = query, count = count)



        for tweet in fetched_tweets:

            parsed_tweet = {}



            parsed_tweet['text'] = tweet.text

            parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)



            if tweet.retweet_count > 0:

                if parsed_tweet not in tweets:

                    tweets.append(parsed_tweet)

            else:

                tweets.append(parsed_tweet)



        return tweets


    except tweepy.TweepError as e:

        print("Error : " + str(e))

def main():

client = TwitterClient()

tweets = client.get_tweets(query = 'Dengue', count = 200)


# picking positive tweets from tweets

# percentage of positive tweets

打印("正推文百分比:{}%" .format(100 * len(ptweets)/ len(推文)))

# picking negative tweets from tweets

ntweets = [如果推文发送推文推文['情绪'] =='否定']

# percentage of negative tweets

打印("否定推文百分比:{}%" .format(100 * len(ntweets)/ len(推文)))

# percentage of neutral tweets

打印("中性推文百分比:{}%\

    ".format(100*len(tweets - ntweets - ptweets)/len(tweets)))


# printing first 5 positive tweets

打印(" \ n \ n正面推文:")

在ptweets中发推文[:10]:

    print(tweet['text'])


# printing first 5 negative tweets

打印(" \ n \ n否定推文:")

在ntweets中发推文[:10]:

    print(tweet['text'])

如果名称 ==" 主要":

# calling main function

    main()