使用Python程式設計進行Twitter情緒分析。
情緒分析是評估人們透過書面文字或口頭交流對特定事件反饋的情緒的過程。當然,口頭交流也必須轉換為書面文字,以便可以透過Python程式進行分析。人們表達的情緒可能是積極的或消極的。透過對情緒文字中不同單詞賦予權重,我們計算出一個數值,這給了我們對情緒的數學評估。
實用性
客戶反饋 − 瞭解客戶對產品或服務的意見對於企業至關重要。當客戶的反饋以書面文字的形式提供時,我們可以在Twitter上執行情緒分析,以程式設計方式找出整體反饋是正面還是負面,並採取糾正措施。
政治活動 − 對於政治對手來說,瞭解他們發表演講的物件的反應至關重要。如果可以透過社交媒體等線上平臺收集公眾的反饋,那麼我們可以判斷公眾對特定演講的反應。
政府舉措 − 當政府不時實施新計劃時,他們可以通過了解民意來判斷對新計劃的反應。公眾常常透過Twitter表達他們的讚揚或不滿。
方法
下面列出了使用Python構建情緒分析程式所需的步驟。
首先,我們安裝Tweepy和TextBlob。此模組將幫助我們從Twitter收集資料,以及提取文字並進行處理。
驗證Twitter。我們需要使用API金鑰才能從Twitter提取資料。
然後,我們根據推文中的文字將推文分類為正面推文和負面推文。
示例
import re import tweepy from tweepy import OAuthHandler from textblob import TextBlob class Twitter_User(object): def __init__(self): consumer_key = '1ZG44GWXXXXXXXXXjUIdse' consumer_secret = 'M59RI68XXXXXXXXXXXXXXXXV0P1L6l7WWetC' access_token = '865439532XXXXXXXXXX9wQbgklJ8LTyo3PhVDtF' access_token_secret = 'hbnBOz5XXXXXXXXXXXXXefIUIMrFVoc' try: self.auth = OAuthHandler(consumer_key, consumer_secret) self.auth.set_access_token(access_token, access_token_secret) self.api = tweepy.API(self.auth) except: print("Error: Authentication Failed") def pristine_tweet(self, twitter): return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", twitter).split()) def Sentiment_Analysis(self, twitter): audit = TextBlob(self.pristine_tweet(twitter)) # set sentiment if audit.sentiment.polarity > 0: return 'positive' elif audit.sentiment.polarity == 0: return 'negative' def tweet_analysis(self, query, count = 10): twitter_tweets = [] try: get_twitter = self.api.search(q = query, count = count) for tweets in get_twitter: inspect_tweet = {} inspect_tweet['text'] = tweets.text inspect_tweet['sentiment'] = self.Sentiment_Analysis(tweets.text) if tweets.retweet_count > 0: if inspect_tweet not in twitter_tweets: twitter_tweets.append(inspect_tweet) else: twitter_tweets.append(inspect_tweet) return twitter_tweets except tweepy.TweepError as e: print("Error : " + str(e)) def main(): api = Twitter_User() twitter_tweets = api.tweet_analysis(query = 'Ram Nath Kovind', count = 200) Positive_tweets = [tweet for tweet in twitter_tweets if tweet['sentiment'] == 'positive'] print("Positive tweets percentage: {} %".format(100*len(Positive_tweets)/len(twitter_tweets))) Negative_tweets = [tweet for tweet in twitter_tweets if tweet['sentiment'] == 'negative'] print("Negative tweets percentage: {} %".format(100*len(Negative_tweets)/len(twitter_tweets))) print("\n\nPositive_tweets:") for tweet in Positive_tweets[:10]: print(tweet['text']) print("\n\nNegative_tweets:") for tweet in Negative_tweets[:10]: print(tweet['text']) if __name__ == "__main__": main()
輸出
執行上述程式碼會得到以下結果:
Positive tweets percentage: 48.78048780487805 % Negative tweets percentage: 46.34146341463415 % Positive_tweets: RT @heartful_ness: "@kanhashantivan presents a model of holistic living. My deep & intimate association with this organisation goes back to… RT @heartful_ness: Heartfulness Guide @kamleshdaaji welcomes honorable President of India Ram Nath Kovind @rashtrapatibhvn, honorable first… RT @DrTamilisaiGuv: Very much pleased by the affection shown by our Honourable President Sri Ram Nath Kovind and First Lady madam Savita Ko… RT @BORN4WIN: Who became the first President of India from dalit community? A) K.R. Narayanan B) V. Venkata Giri C) R. Venkataraman D) Ram… Negative_tweets: RT @Keyadas63: What wuld those #empoweredwomen b termed who reach Hon HC at the drop of a hat But Demand #Alimony Maint? @MyNation_net @vaa… RT @heartful_ness: Thousands of @heartful_ness practitioners meditated with Heartfulness Guide @kamleshdaaji at @kanhashantivan & await the… RT @TurkeyinDelhi: Ambassador Sakir Ozkan Torunlar attended the Joint Session of Parliament of #India and listened the address of H.E. Shri…
廣告