Find the emotions in text for any twitter account, Trump, Biden and Obama case study

By Using this code, you can calculate the emotions from the text.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import itertools
import collections
import twitter
import seaborn as sns
import tweepy as tw
import nltk
from nltk.corpus import stopwords
import warnings
import re
import text2emotion as te


consumer_key= 'Enter your consumer_key'
consumer_secret= 'Enter your consumer_secret'
access_token= 'Enter your access_token'
access_token_secret= 'Enter your access_token_secret'

auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth, wait_on_rate_limit=True)

api = twitter.Api(consumer_key=consumer_key,

#write  the twitter account name
Account_name  = "@BarackObama"  
keepres = api.GetUserTimeline(screen_name = Account_name, count=200)

# create lists to save the emotions type for each tweets 
Happylst = []
Angrylst = []
Surprist= []
Sadlst = []
Fearlst= []
keep_Happyx = 0
keep_Angryx = 0
keep_Surprisex = 0
keep_Sadx = 0
keep_Fearx = 0

all_tweets = []
tweets = [i.AsDict() for i in keepres]
for t in tweets:

# remove links, clean the tweets
def remove_url(txt):
    return " ".join(re.sub("([^0-9A-Za-z \t])|(\w+:\/\/\S+)", "", txt).split())

all_tweets_no_urls = [remove_url(tweet) for tweet in all_tweets]

for t in all_tweets_no_urls:
    keepemo = te.get_emotion(t)
# find the maximum feeling in each tweet
def find_maxemotion(Happyx, Angryx,  Surprisex, Sadx, Fearx ):
    res_max = ''
    res_max_value = 0
    if Happyx > Angryx and Happyx > Surprisex and Happyx > Sadx and Happyx > Fearx:
        res_max = 'Happy'
        #res_max_value = Happyx
    if Angryx > Happyx and Angryx > Surprisex and Angryx > Sadx and Angryx > Fearx:
        res_max = 'Angry'
        #res_max_value = Angryx
    if Surprisex > Happyx and Surprisex > Angryx and Surprisex > Sadx and Surprisex > Fearx:
        res_max = 'Surprise'
        #res_max_value = Surprisex
    if Sadx > Happyx and Sadx > Angryx and Sadx > Surprisex and Sadx > Fearx:
        res_max = 'Sad'
        #res_max_value = Sadx
    if Fearx > Happyx and Fearx > Angryx and Fearx > Surprisex and Fearx > Sadx:
        res_max = 'Fear'
        #res_max_value = Fearx
    return res_max

for t in all_tweets_no_urls:
    keepemo = te.get_emotion(t)
    emres = find_maxemotion(keepemo['Happy'], keepemo['Angry'], keepemo['Surprise'], keepemo['Sad'], keepemo['Fear'])
    if emres == 'Happy':
        keep_Happyx += 1

    if emres == 'Angry':
        keep_Angryx += 1
    if emres == 'Surprise':
        keep_Surprisex += 1
    if emres == 'Sad':
        keep_Sadx += 1

    if emres == 'Fear':
        keep_Fearx += 1

print('Finish reading')
# print number of each emotion
print('Happy', keep_Happyx)
print('Angry', keep_Angryx)
print('Surprise', keep_Surprisex)
print('Sad', keep_Sadx)
print('Fear', keep_Fearx)
# print the first 4 tweets 
['Banking Marketplace Making a Wise Pivot Banking is necessary banks are not',
 'The aim is to enable people to discover whether the doctors and hospitals they visit may have motives other than pa',
 'Civilized people respect others Civilized people know the limits of their freedom of speech Your freedom ends w',
 'PayPal to allow cryptocurrency buying selling and shopping on its network']
# The result in chart
import matplotlib.pyplot as plt
names = ['Happy', 'Angry', 'Surprise', 'Sad','Fear']
values_1 = []
x =[]
for xc in range(len(y1)):
plt.figure(figsize=(30, 9))
plt.bar(names, values_1)
plt.title(Account_name + " Emotions ")

plt.title( Account_name  + " Emotions - Happy (green), Fear (red)" )
plt.plot(x, Happylst,  marker='o', color="green",  markersize=2, linewidth=2 , label="Happy")
plt.plot(x, Fearlst,  marker='o', color="red",  markersize=2, linewidth=2 , label="Fear")

Biden tweets:

# the last 4 Tweetes
'RT BarackObama Dont boo vote Happy Halloween everybody',
 'President Obama and I left President Trump a playbook on how to deal with pandemics He flatout ignored it And we',
 'If youre planning to vote early inperson today is your last day to do so in many states Head to',
 'RT TeamJoe Voting Update Early vote hours have been extended in Douglas County NE to 500 PM today Find your early voting location a']

Trump tweets:

#the last 4 tweets:
['Biden & Obama owe a massive apology to the People of Flint The water was poisoned on their watch Not only did the',
 'Bidens plan to Abolish American Energy is an economic DEATH SENTENCE for Pennsylvania A vote for Biden is a vote',
 'Our ECONOMY is now surging back faster better bigger and stronger than any nation on earth We just had the best',
 'I ran for office 4 years ago because I could not sit by amp watch any longer as a small group of Washington Insiders']

Obama tweets:

#the last 4 tweets:
['Dont boo vote Happy Halloween everybody',
 'Three days Michigan Three days until the most important election of our lifetimes Join me and JoeBiden for our',
 'You could be the difference between someone making it out to the polls or staying home And many states could be de',
 'Always great talking to KingJames and MavCarter about everything from this unique NBA season to the importance of']
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     (adsbygoogle = window.adsbygoogle || []).push({});

الصورة الرمزية لـ admin

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *