Find the emotions in text , Trump, Biden and Obama case study

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


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
 
warnings.filterwarnings("ignore")
sns.set(font_scale=1.5)
sns.set_style("whitegrid")

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,
  consumer_secret=consumer_secret,
  access_token_key=access_token,
  access_token_secret=access_token_secret)


#write  the twitter account name
Account_name  = "@accountid"  
 
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:
    all_tweets.append(t['text'])

 
# 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)
    Happylst.append(keepemo['Happy'])
    Angrylst.append(keepemo['Angry'])
    Surprist.append(keepemo['Surprise'])
    Sadlst.append(keepemo['Sad'])
    Fearlst.append(keepemo['Fear'])

# 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'])
    Happylst.append(keepemo['Happy'])
    Angrylst.append(keepemo['Angry'])
    Surprist.append(keepemo['Surprise'])
    Sadlst.append(keepemo['Sad'])
    Fearlst.append(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 
all_tweets_no_urls[4]

Result:
['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 = []
values_1.append(keep_Happyx)
values_1.append(keep_Angryx)
values_1.append(keep_Surprisex)
values_1.append(keep_Sadx)
values_1.append(keep_Fearx)
   
x =[]
for xc in range(len(y1)):
    x.append(xc)
    
plt.figure(figsize=(30, 9))
plt.subplot(131)
plt.bar(names, values_1)
plt.title(Account_name + " Emotions ")


plt.subplot(132)
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']

Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Rits Blog by Crimson Themes.