-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentiment Analysis
More file actions
93 lines (61 loc) · 1.77 KB
/
Sentiment Analysis
File metadata and controls
93 lines (61 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import tweepy
from textblob import TextBlob
from wordcloud import WordCloud
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
#Api credentials
consumerkey=''
consumerSecret=''
accesstoken=''
accesstokensecret=''
#Auth object
authenticate=tweepy.OAuthHandler(consumerkey,consumerSecret)
#Access Token set
authenticate.set_access_token(accesstoken,accesstokensecret)
#Api object while passing auth info
api=tweepy.API(authenticate,wait_on_rate_limit=True)
#Extract tweets from the twitter user
posts=api.user_timeline(screen_name="Trump", count=100, lang='en', tweet_mode='extended')
#Print tweets
i=1
for tweet in posts:
print(str(i) + ')' + tweet.full_text + "\n")
i=i+1
#create a data frame for tweets
df=pd.DataFrame([tweet.full_text for tweet in posts],columns=['Tweets'])
#show first 5
df.head()
#clean text
def cleantxt(text):
text=re.sub(r'@[A-Za-z0-9]+', '' ,text) # remove
text=re.sub(r'#','',text) #Removing '#'
text=re.sub(r'RT[\s]+','',text) # Removing RT
text=re.sub(r'https:\/\/\s+','',text) # Removing hyperlink
return text
#Applying
df['Tweets']=df['Tweets'].apply(cleantxt)
#show clean text
df
#get subjectivity
def getsubj(text):
return TextBlob(text).sentiment.subjectivity
#get polarity
def getpol(text):
return TextBlob(text).sentiment.polarity
#create new columns
df['Subjectivity']=df['Tweets'].apply(getsubj)
df['polarity']=df['Tweets'].apply(getpol)
#print
df
#get positivity
def positivity(score):
if score<0:
return 'Negative'
elif score==0:
return 'Neutral'
else:
return 'Positive'
df['Analysis']=df['polarity'].apply(positivity)