-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProject 1.py
executable file
·305 lines (214 loc) · 8.91 KB
/
Project 1.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 20 14:24:34 2018
@author: eamonnkeane
"""
#--------------------------------------- Part A ---------------------------------------#
from twython import TwythonStreamer
import sys
import json
from pprint import pprint
from collections import Counter
tweets = []
class MyStreamer(TwythonStreamer):
'''our own subclass of TwythonStreamer'''
# overriding
def on_success(self, data):
if 'lang' in data and data['lang'] == 'en':
tweets.append(data)
print('received tweet #', len(tweets), data['text'][:100])
if len(tweets) >= 10000:
self.store_json()
self.disconnect()
# overriding
def on_error(self, status_code, data):
print(status_code, data)
self.disconnect()
def store_json(self):
with open('tweet_stream_{}_{}.json'.format(keyword, len(tweets)), 'w') as f:
json.dump(tweets, f, indent=4)
if __name__ == '__main__':
CONSUMER_KEY = "JY9tYsOGKlvqmEE8tkyfxuFoV"
CONSUMER_SECRET = "adWL6WvLGoB1l4FFSVlgixrnv2TQwR9ZFcCEvdc7wXejSpa8NK"
ACCESS_TOKEN = "973673059205853184-iLb9xPmtcAlhfLG3EHgpzCYiSZ8JpzT"
ACCESS_TOKEN_SECRET = "j9Ictf8VEMaFoENAnHeBb0bPYUgDWmmY1FGxnuhih1ybM"
stream = MyStreamer(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
if len(sys.argv) > 1:
keyword = sys.argv[1]
else:
keyword = 'Instagram'
stream.statuses.filter(track=keyword)
#--------------------------------------- Part B ---------------------------------------#
# a.) What are the ten most popular words with and without stop words?
# remove punctations
import nltk
import string
from twython import TwythonStreamer
import sys
import json
from pprint import pprint
from collections import Counter
def popular_words(filename):
with open(filename, 'r') as infile:
data = json.load(infile)
type(data[0])
data[0].keys()
lst_words = []
for tweet in data:
lst_words.extend(tweet['text'].split())
words = nltk.word_tokenize(str(lst_words).lower())
stopwords = nltk.corpus.stopwords.words('english')
extra_words = ['https', 'rt', 'facebook']
stopwords.extend(extra_words)
words = [''.join(c for c in s if c not in string.punctuation) for s in words]
# Source: https://stackoverflow.com/questions/4371231/removing-punctuation-from-python-list-items
words = [s for s in words if s]
no_stopwords = []
for w in words:
if w not in stopwords and len(w) > 1:
no_stopwords.append(w)
with_stopwords = []
for w in words:
if w != "'" and len(w) > 1:
with_stopwords.append(w)
print("With Stop Words")
freq = nltk.FreqDist(with_stopwords)
freq.plot(10)
print("Without Stop Words")
freq1 = nltk.FreqDist(no_stopwords)
freq1.plot(10)
popular_words("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Instagram_10000.json")
popular_words("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Snapchat_10000.json")
# b.) What are the ten most popular hashtags (#hashtag)?
def popular_hashtags(filename):
with open(filename, 'r') as infile:
data = json.load(infile)
type(data[0])
data[0].keys()
mention_list = []
for tweet in data:
mentions = tweet['entities']['hashtags']
for ment in mentions:
mention_list.append(ment['text'])
c = Counter(mention_list)
return c.most_common(10)
popular_hashtags("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Instagram_10000.json")
popular_hashtags("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Snapchat_10000.json")
# c.) What are the ten most frequently appearing usernames (@username)?
def frequent_usernames(filename):
with open(filename, 'r') as infile:
data = json.load(infile)
type(data[0])
data[0].keys()
mention_list = []
for tweet in data:
mentions = tweet['entities']['user_mentions']
for ment in mentions:
mention_list.append(ment['screen_name'])
c = Counter(mention_list)
return c.most_common(10)
frequent_usernames("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Instagram_10000.json")
frequent_usernames("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Snapchat_10000.json")
# d. Who is the most frequently tweeting person about the keyword?
def frequent_tweeter(filename):
with open(filename, 'r') as infile:
data = json.load(infile)
type(data[0])
data[0].keys()
mention_list = []
for tweet in data:
mention_list.append(tweet['user']['screen_name'])
c = Counter(mention_list)
return c.most_common(1)
frequent_tweeter("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Instagram_10000.json")
frequent_tweeter("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Snapchat_10000.json")
# e. Which is the most influential tweet? (Let’s define that influence is the sum
# of retweet count, reply count, and quote count.)
def most_influential_tweet(filename):
with open(filename, 'r') as infile:
data = json.load(infile)
type(data[0])
data[0].keys()
counts = []
t_text = []
for tweet in data:
retweet_count = tweet['retweet_count']
reply_count = tweet['reply_count']
quote_count = tweet['quote_count']
tweet_text = tweet['text']
counts.append(retweet_count + reply_count + quote_count)
t_text.append(tweet_text)
return t_text[counts.index(max(counts))]
most_influential_tweet("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Instagram_100.json")
most_influential_tweet("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Snapchat_100.json")
#--------------------------------------- Part C ---------------------------------------#
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import nltk
import numpy as np
import matplotlib.pyplot as plt
from os import path
from PIL import Image
def word_cloud(filename):
with open(filename, 'r') as infile:
data = json.load(infile)
type(data[0])
data[0].keys()
lst_words = []
for tweet in data:
lst_words.extend(tweet['text'].split())
stopwords = nltk.corpus.stopwords.words('english')
new_stop_words = ['https', 'might']
stopwords.extend(new_stop_words)
text = lst_words
text2 = ''
for word in text:
if len(word) == 1 or word in stopwords:
continue
if word.startswith('https'):
continue
if word.startswith('RT'):
continue
text2 += ' {}'.format(word)
wordcloud = WordCloud().generate(text2)
plt.figure()
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.figure()
plt.show()
word_cloud("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Instagram_100.json")
word_cloud("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Snapchat_100.json")
#--------------------------------------- Part D ---------------------------------------#
# Using TextBlob, calculate the polarity and
#subjectivity scores for each tweet in the 10K+10K tweet corpus. Summarize the
#calculated scores with histograms using Matplotlib, where X-axis is the score and
#Y-axis is the tweet count in the score bin. Also, provide the average of the
#polarity and subjectivity scores.
def polarity_and_subjectivity_scores(filename):
from textblob import TextBlob
with open(filename) as infile:
content = infile.read()
sentences = content.split('\n')
print(len(sentences), sentences[0], sentences[-1], sep="\n")
sub_list = []
pol_list = []
for s in sentences:
tb = TextBlob(s)
sub_list.append(tb.sentiment.subjectivity)
pol_list.append(tb.sentiment.polarity)
import matplotlib.pyplot as plt
plt.hist(sub_list, bins=10) #, normed=1, alpha=0.75)
plt.xlabel('Subjectivity Score')
plt.ylabel('Sentence Count')
plt.grid(True)
plt.savefig('subjectivity.pdf')
plt.show()
plt.hist(pol_list, bins=10) #, normed=1, alpha=0.75)
plt.xlabel('Polarity Score')
plt.ylabel('Sentence Count')
plt.grid(True)
plt.savefig('polarity.pdf')
plt.show()
polarity_and_subjectivity_scores("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Instagram_100.json")
polarity_and_subjectivity_scores("/Users/eamonnkeane/Desktop/UBC/Year 3/COMM 337/Project 1/tweet_stream_Snapchat_100.json")