Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Phân tích cảm xúc Twitter (Twitter Sentiment Analysis) bằng Python

Phân tích cảm xúc (Sentiment Analysis) là quá trình ước lượng cảm xúc của mọi người đưa ra phản hồi về sự kiện nhất định qua văn bản viết hoặc giao tiếp nói. Tất nhiên, giao tiếp nói cũng phải chuyển thành văn bản để phân tích bằng chương trình Python. Cảm xúc thể hiện có thể tích cực hoặc tiêu cực. Bằng cách gán trọng số cho các từ khác nhau trong văn bản cảm xúc, ta tính giá trị số và có đánh giá toán học về cảm xúc.

Tính hữu ích

  • Phản hồi khách hàng - Quan trọng đối với doanh nghiệp biết ý kiến khách hàng về sản phẩm/dịch vụ. Khi phản hồi có sẵn dưới dạng văn bản, có thể chạy phân tích cảm xúc trên Twitter để tìm ra tổng thể phản hồi tích cực/tiêu cực và hành động khắc phục.
  • Chiến dịch chính trị - Đối thủ chính trị cần biết phản ứng của người nghe bài phát biểu. Nếu phản hồi từ công chúng thu thập được qua mạng xã hội, có thể đánh giá phản ứng công chúng đối với bài phát biểu cụ thể.
  • Chính sách chính phủ - Khi chính phủ triển khai các kế hoạch mới, có thể đánh giá phản ứng dư luận bằng cách thu thập ý kiến công chúng. Thường dân chúng bày tỏ khen ngợi hoặc giận dữ qua Twitter.

Cách tiếp cận

Dưới đây là các bước cần thiết để xây dựng chương trình phân tích cảm xúc trong Python.

  • Cài đặt Tweepy và TextBlob. Module này giúp thu thập dữ liệu từ Twitter cũng như trích xuất và xử lý văn bản.
  • Xác thực với Twitter. Cần dùng API keys để trích xuất dữ liệu từ Twitter.
  • Phân loại tweet thành tích cực và tiêu cực dựa trên văn bản trong tweet.

Ví dụ

import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob

class Twitter_User(object):
    def __init__(self):
        self.consumer_key = '1ZG44GWXXXXXXXXXjUIdse'
        self.consumer_secret = 'M59RI68XXXXXXXXXXXXXXXXV0P1L6l7WWetC'
        self.access_token = '865439532XXXXXXXXXX9wQbgklJ8LTyo3PhVDtF'
        self.access_token_secret = 'hbnBOz5XXXXXXXXXXXXXefIUIMrFVoc'
        try:
            self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
            self.auth.set_access_token(self.access_token, self.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))
        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()

Kết quả

Chạy đoạn code trên cho kết quả sau:

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...