forked from harit198/Tweet-Analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
331 lines (145 loc) · 6.74 KB
/
app.py
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import streamlit as st
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
from PIL import Image
import seaborn as sns
consumerKey = #confidential
consumerSecret = #confidential
accessToken = #confidential
accessTokenSecret = #confidential
#Create the authentication object
authenticate = tweepy.OAuthHandler(consumerKey, consumerSecret)
# Set the access token and access token secret
authenticate.set_access_token(accessToken, accessTokenSecret)
# Creating the API object while passing in auth information
api = tweepy.API(authenticate, wait_on_rate_limit = True)
#plt.style.use('fivethirtyeight')
def app():
st.title("Tweet Analyzer 🔥")
activities=["Tweet Analyzer","Generate Twitter Data"]
choice = st.sidebar.selectbox("Select Your Activity",activities)
if choice=="Tweet Analyzer":
st.subheader("Analyze the tweets of your favourite Personalities")
st.subheader("This tool performs the following tasks :")
st.write("1. Fetches the 5 most recent tweets from the given twitter handel")
st.write("2. Generates a Word Cloud")
st.write("3. Performs Sentiment Analysis a displays it in form of a Bar Graph")
raw_text = st.text_area("Enter the exact twitter handle of the Personality (without @)")
st.markdown("<-------- Also Do checkout the another cool tool from the sidebar")
Analyzer_choice = st.selectbox("Select the Activities", ["Show Recent Tweets","Generate WordCloud" ,"Visualize the Sentiment Analysis"])
if st.button("Analyze"):
if Analyzer_choice == "Show Recent Tweets":
st.success("Fetching last 5 Tweets")
def Show_Recent_Tweets(raw_text):
# Extract 100 tweets from the twitter user
posts = api.user_timeline(screen_name=raw_text, count = 100, lang ="en", tweet_mode="extended")
def get_tweets():
l=[]
i=1
for tweet in posts[:5]:
l.append(tweet.full_text)
i= i+1
return l
recent_tweets=get_tweets()
return recent_tweets
recent_tweets= Show_Recent_Tweets(raw_text)
st.write(recent_tweets)
elif Analyzer_choice=="Generate WordCloud":
st.success("Generating Word Cloud")
def gen_wordcloud():
posts = api.user_timeline(screen_name=raw_text, count = 100, lang ="en", tweet_mode="extended")
# Create a dataframe with a column called Tweets
df = pd.DataFrame([tweet.full_text for tweet in posts], columns=['Tweets'])
# word cloud visualization
allWords = ' '.join([twts for twts in df['Tweets']])
wordCloud = WordCloud(width=500, height=300, random_state=21, max_font_size=110).generate(allWords)
plt.imshow(wordCloud, interpolation="bilinear")
plt.axis('off')
plt.savefig('WC.jpg')
img= Image.open("WC.jpg")
return img
img=gen_wordcloud()
st.image(img)
else:
def Plot_Analysis():
st.success("Generating Visualisation for Sentiment Analysis")
posts = api.user_timeline(screen_name=raw_text, count = 100, lang ="en", tweet_mode="extended")
df = pd.DataFrame([tweet.full_text for tweet in posts], columns=['Tweets'])
# Create a function to clean the tweets
def cleanTxt(text):
text = re.sub('@[A-Za-z0–9]+', '', text) #Removing @mentions
text = re.sub('#', '', text) # Removing '#' hash tag
text = re.sub('RT[\s]+', '', text) # Removing RT
text = re.sub('https?:\/\/\S+', '', text) # Removing hyperlink
return text
# Clean the tweets
df['Tweets'] = df['Tweets'].apply(cleanTxt)
def getSubjectivity(text):
return TextBlob(text).sentiment.subjectivity
# Create a function to get the polarity
def getPolarity(text):
return TextBlob(text).sentiment.polarity
# Create two new columns 'Subjectivity' & 'Polarity'
df['Subjectivity'] = df['Tweets'].apply(getSubjectivity)
df['Polarity'] = df['Tweets'].apply(getPolarity)
def getAnalysis(score):
if score < 0:
return 'Negative'
elif score == 0:
return 'Neutral'
else:
return 'Positive'
df['Analysis'] = df['Polarity'].apply(getAnalysis)
return df
df= Plot_Analysis()
st.write(sns.countplot(x=df["Analysis"],data=df))
st.pyplot(use_container_width=True)
else:
st.subheader("This tool fetches the last 100 tweets from the twitter handel & Performs the following tasks")
st.write("1. Converts it into a DataFrame")
st.write("2. Cleans the text")
st.write("3. Analyzes Subjectivity of tweets and adds an additional column for it")
st.write("4. Analyzes Polarity of tweets and adds an additional column for it")
st.write("5. Analyzes Sentiments of tweets and adds an additional column for it")
user_name = st.text_area("*Enter the exact twitter handle of the Personality (without @)*")
st.markdown("<-------- Also Do checkout the another cool tool from the sidebar")
def get_data(user_name):
posts = api.user_timeline(screen_name=user_name, count = 100, lang ="en", tweet_mode="extended")
df = pd.DataFrame([tweet.full_text for tweet in posts], columns=['Tweets'])
def cleanTxt(text):
text = re.sub('@[A-Za-z0–9]+', '', text) #Removing @mentions
text = re.sub('#', '', text) # Removing '#' hash tag
text = re.sub('RT[\s]+', '', text) # Removing RT
text = re.sub('https?:\/\/\S+', '', text) # Removing hyperlink
return text
# Clean the tweets
df['Tweets'] = df['Tweets'].apply(cleanTxt)
def getSubjectivity(text):
return TextBlob(text).sentiment.subjectivity
# Create a function to get the polarity
def getPolarity(text):
return TextBlob(text).sentiment.polarity
# Create two new columns 'Subjectivity' & 'Polarity'
df['Subjectivity'] = df['Tweets'].apply(getSubjectivity)
df['Polarity'] = df['Tweets'].apply(getPolarity)
def getAnalysis(score):
if score < 0:
return 'Negative'
elif score == 0:
return 'Neutral'
else:
return 'Positive'
df['Analysis'] = df['Polarity'].apply(getAnalysis)
return df
if st.button("Show Data"):
st.success("Fetching Last 100 Tweets")
df=get_data(user_name)
st.write(df)
st.subheader(' ------------------------Created By : HARIT SHANDILYA ---------------------- :sunglasses:')
if __name__ == "__main__":
app()