-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
87 lines (74 loc) · 2.41 KB
/
main.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
import numpy as np
from sklearn.cluster import KMeans
from indexer import Indexer
from afinn import Afinn
import pandas as pd
numberOfPages = 50
def convertIndex(index: dict[str, list[int]], termIndexMap: dict[str, int]):
n = len(termIndexMap)
array = np.zeros([numberOfPages, n], dtype=int)
for term in index:
termIndex = termIndexMap[term]
postingList = index[term]
for postingId in postingList:
array[postingId, termIndex] += 1
return array
indexer = Indexer(50)
index, termIndexMap = indexer.build()
X = convertIndex(index, termIndexMap)
kmeans3 = KMeans(n_clusters=3, random_state=0).fit(X)
kmeans6 = KMeans(n_clusters=6, random_state=0).fit(X)
afn = Afinn()
pages = []
for i in range(0, numberOfPages):
try:
text = open('pages/' + str(i) + '.txt', 'r').read()
temp = text.split()
text = ' '.join(temp)
pages.append(text)
except:
continue
scores = [afn.score(article) for article in pages]
sentiment = ['positive' if score > 0
else 'negative' if score < 0
else 'neutral'
for score in scores]
def printData(pages, scores, sentiment, labels):
df = pd.DataFrame()
df['cluster'] = labels
df['pages'] = pages
df['scores'] = scores
df['sentiments'] = sentiment
print(df)
map = {}
for i in range(0, numberOfPages):
cluster = labels[i]
if (cluster not in map):
map[cluster] = {
"count": 1,
"totalScore": scores[i],
"averageScore": scores[i]
}
else:
oldScore = map[cluster]["totalScore"]
oldCount = map[cluster]["count"]
newScore = oldScore + scores[i]
newCount = oldCount + 1
newAverage = newScore/newCount
map[cluster] = {
"count": newCount,
"totalScore": newScore,
"averageScore": newAverage,
}
df1 = pd.DataFrame()
clusterValues = []
averageScores = []
for key in map:
clusterValues.append(key)
averageScores.append(map[key]["averageScore"])
df1["cluster"] = clusterValues
df1["avg sentiment"] = averageScores
print(df1)
return
printData(pages, scores, sentiment, kmeans3.labels_)
printData(pages, scores, sentiment, kmeans6.labels_)