-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitcointalk_sentiment_classifier.py
More file actions
164 lines (136 loc) · 5.52 KB
/
bitcointalk_sentiment_classifier.py
File metadata and controls
164 lines (136 loc) · 5.52 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
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
import pandas as pd
from datetime import datetime
from datetime import timedelta
import json
import getopt
import sys
import pickle
import warnings
import os
def main(argv):
warnings.filterwarnings('ignore', category=DeprecationWarning)
input_file = ''
model_file = ''
output_folder = ''
output_posts = ''
try:
opts, args = getopt.getopt(argv, "hi:m:f:n:")
except getopt.GetoptError:
print('bitcointalk_sentiment_classifier.py -i <inputfile> -m <model> -f <output folder> -n <number of output posts [number|fraction|all]>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('bitcointalk_sentiment_classifier.py -i <inputfile> -m <model> -f <output folder> -n <number of output posts [number|fraction|all]>')
sys.exit()
elif opt == '-i':
input_file = arg
elif opt == '-m':
model_file = arg
elif opt == '-f':
output_folder = arg
elif opt == '-n':
output_posts = arg
classify(input_file, model_file, output_folder, output_posts)
def transform_sentiment_dict(sentiment_dict):
negative = []
neutral = []
positive = []
sorted_dates = sorted(list(sentiment_dict.keys()))
point_start = datetime.strptime(sorted_dates[0], '%Y-%m-%d').timestamp()
dates_parsed = [datetime.strptime(date, '%Y-%m-%d') for date in sorted_dates]
date = datetime.strptime(sorted_dates[0], '%Y-%m-%d')
while date <= dates_parsed[-1]:
if date in dates_parsed:
negative.append(sentiment_dict[str(date.date())]['negative'])
neutral.append(sentiment_dict[str(date.date())]['neutral'])
positive.append(sentiment_dict[str(date.date())]['positive'])
else:
negative.append(0)
neutral.append(0)
positive.append(0)
date += timedelta(days=1)
new_dict = {'heading': '',
'chart':
{'negative': negative,
'neutral': neutral,
'positive': positive},
'pointStart': int(point_start*100)
}
return(new_dict)
def classify(input_file, model_file, output_folder, output_posts):
topic_df = pd.read_json(input_file, orient='index', convert_dates=False)
with open(model_file, 'rb') as file:
model = pickle.load(file)
topic_df['smoothed_text'] = topic_df['text'].apply(lambda x: x + ' <smoothingplaceholder>')
topic_df['Sentiment'] = model.predict(topic_df['smoothed_text'])
topic_df.drop(labels=['smoothed_text'], axis=1, inplace=True)
def checkTimeFormat(time_string):
try:
datetime.strptime(time_string,'%B %d, %Y, %I:%M:%S %p')
return True
except ValueError:
return False
topic_df['date'] = topic_df['date'].apply(str)
topic_df = topic_df[topic_df['date'].apply(lambda x: checkTimeFormat(x))]
topic_df['date'] = topic_df['date'].apply(lambda x: datetime.strptime(x,'%B %d, %Y, %I:%M:%S %p').date())
day_groups = topic_df.groupby(['date'])
dates = []
positives = []
neutral = []
negatives = []
for key, group in day_groups:
dates.append(key)
if 0 in group['Sentiment'].value_counts().index:
negatives.append(group['Sentiment'].value_counts()[0])
else:
negatives.append(0)
if 1 in group['Sentiment'].value_counts().index:
neutral.append(group['Sentiment'].value_counts()[1])
else:
neutral.append(0)
if 2 in group['Sentiment'].value_counts().index:
positives.append(group['Sentiment'].value_counts()[2])
else:
positives.append(0)
json_sentiment = {}
for i in range(len(dates)):
string_date = str(dates[i])
json_sentiment[string_date] = {}
json_sentiment[string_date]['positive'] = int(positives[i])
json_sentiment[string_date]['neutral'] = int(neutral[i])
json_sentiment[string_date]['negative'] = int(negatives[i])
_, topic_name = os.path.split(input_file)
topic_name = topic_name.split('.')[0]
topic_df['date'].apply(str)
topic_df.sort_values(by='date', ascending=False, inplace=True)
try:
posts_count = int(output_posts)
if posts_count > len(topic_df):
print('The number in the argument is bigger than actual number of posts. Outputting all posts.')
topic_df_slice = topic_df
else:
topic_df_slice = topic_df[0:posts_count]
except:
try:
posts_count = float(output_posts)
if posts_count > 1:
print('The fraction in the argument is bigger than 1. Outputting all posts.')
topic_df_slice = topic_df
else:
topic_df_slice = topic_df[0:int(posts_count*len(topic_df))]
except:
topic_df_slice = topic_df
if output_posts != 'all':
print('Invalid number of posts value. Outputting all posts.')
file_name = os.path.join(output_folder, 'S{}.json'.format(topic_name))
with open(file_name, 'w') as f:
json.dump(transform_sentiment_dict(json_sentiment), f, ensure_ascii=False)
print('Saved sentiment counts to {}'.format(file_name))
f.close()
file_name = os.path.join(output_folder, 'D{}.json'.format(topic_name))
with open(file_name, 'w') as f:
topic_df_slice.to_json(f, orient='index')
print('Saved posts with sentiments to {}'.format(file_name))
f.close()
if __name__ == "__main__":
main(sys.argv[1:])