-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhackernewsv4.py
220 lines (152 loc) · 5.75 KB
/
hackernewsv4.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
# -*- coding: utf-8 -*-
"""HackerNewsV4.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1dtIIRFFq81O97i6azALZbqBYgoVsUKvD
"""
from warnings import filterwarnings
filterwarnings("ignore")
import pandas as pd
import json
import urllib
import requests
import numpy as np
html = urllib.request.urlopen('https://hacker-news.firebaseio.com/v0/item/2169746.json?print=pretty')
json.loads(html.read())
x = urllib.request.urlopen('https://hacker-news.firebaseio.com/v0/maxitem.json?print=pretty')
max_item = int(x.read())
print(max_item)
data = []
number_of_entries = 1000
min_item = max_item - number_of_entries
count = 0
for i in range(min_item, max_item):
html = urllib.request.urlopen('https://hacker-news.firebaseio.com/v0/item/' + str(i) + '.json')
data.append(json.loads(html.read()))
count += 1
if count % 100 == 0:
print(f"Loaded {count} rows")
print (data[0])
data = [i for i in data if i is not None]
from pandas.io.json import json_normalize
df = pd.DataFrame.from_dict(data)
df.head(10)
print(df.shape)
df.columns
df_new = df.drop(columns = ['deleted', 'dead', 'descendants', 'score', 'kids', 'parent', 'title', 'url'])
df_new.head(10)
df_new['text'][0]
df_comments = df_new[df_new['type'] == 'comment']
df_comments['text']
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.stem import WordNetLemmatizer,PorterStemmer
from nltk.corpus import stopwords
nltk.download('stopwords')
nltk.download('wordnet')
import re
lemmatizer = WordNetLemmatizer()
stemmer = PorterStemmer()
def preprocess(sentence):
sentence=str(sentence)
sentence = sentence.lower()
sentence=sentence.replace('{html}',"")
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', sentence)
rem_url=re.sub(r'http\S+', '',cleantext)
rem_num = re.sub('[0-9]+', '', rem_url)
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(rem_num)
filtered_words = [w for w in tokens if len(w) > 2 if not w in stopwords.words('english')]
stem_words=[stemmer.stem(w) for w in filtered_words]
lemma_words=[lemmatizer.lemmatize(w) for w in stem_words]
return " ".join(filtered_words)
df_comments['clean_text']=df_comments['text'].map(lambda s:preprocess(s))
df_comments.head(10)
df_comments['by'].value_counts()
df_comments.shape
df_comments['text'] = df_comments['text'].astype(str)
df_comments['text'][:10]
df_comments['clean_text'] = df_comments['clean_text'].astype(str)
df_comments['clean_text'][:10]
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
!pip install vaderSentiment
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
def get_compund_score(text):
score = analyzer.polarity_scores(text)
str(text)
return score['compound']
get_compund_score(df_comments['text'][0])
get_compund_score(df_comments['clean_text'][0])
df_comments['vader_score'] = df_comments['text'].apply(get_compund_score)
df_comments['clean_vader_score'] = df_comments['clean_text'].apply(get_compund_score)
df_comments.head(10)
df_comments['sentiment'] = df_comments['vader_score'].apply(lambda c: 'positive' if c >=0 else 'negative')
df_comments['clean_sentiment'] = df_comments['clean_vader_score'].apply(lambda c: 'positive' if c >=0 else 'negative')
df_comments.head(25)
df_comments.to_csv('hn_sentiments.csv')
import pandas as pd
import json
import urllib
import requests
!pip install vaderSentiment
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
def get_compund_score(text):
score = analyzer.polarity_scores(text)
str(text)
return score['compound']
def preprocess(sentence):
sentence=str(sentence)
sentence = sentence.lower()
sentence=sentence.replace('{html}',"")
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', sentence)
rem_url=re.sub(r'http\S+', '',cleantext)
rem_num = re.sub('[0-9]+', '', rem_url)
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(rem_num)
filtered_words = [w for w in tokens if len(w) > 2 if not w in stopwords.words('english')]
stem_words=[stemmer.stem(w) for w in filtered_words]
lemma_words=[lemmatizer.lemmatize(w) for w in stem_words]
return " ".join(filtered_words)
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
import pandas as pd
import json
import urllib
import requests
def get_score(entries):
data = []
for id in entries:
html = urllib.request.urlopen('https://hacker-news.firebaseio.com/v0/item/' + str(id) + '.json')
data.append(json.loads(html.read()))
print(data[0])
data = [i for i in data if i is not None]
df = pd.DataFrame.from_dict(data)
df_comments = df[df['type'] == 'comment']
df_comments['clean_text']=df_comments['text'].map(lambda s:preprocess(s))
df_comments['clean_vader_score'] = df_comments['clean_text'].apply(get_compund_score)
return df_comments['clean_vader_score'].sum() #we can use mean()
import pandas as pd
import json
import urllib
import requests
def get_cummulative_score(username):
data = []
html = urllib.request.urlopen('https://hacker-news.firebaseio.com/v0/user/' + str(username) + '.json?print=pretty')
data.append(json.loads(html.read()))
df2 = pd.DataFrame.from_dict(data)
entries = (df2['submitted'][0])
score = get_score(entries)
return score
score = get_cummulative_score('jl')
print("Cummulative score for user ", score )
test_message = "This is really bad. Never going there again. Absolute worst"
print (get_compund_score(test_message))
test_message = "This is really good. Loved the place. Employees were super kind. Can't wait to go back again."
print (get_compund_score(test_message))