-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsentiment.js
50 lines (39 loc) · 1.11 KB
/
sentiment.js
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
function tokenize(input) {
// convert negative contractions into negate_<word>
return $.map(input.replace('.', '')
.replace('/ {2,}/', ' ')
.replace(/[.,\/#!$%\^&\*;:{}=_`~()]/g, '')
.toLowerCase()
.replace(/\w+['’]t\s+(a\s+)?(.*?)/g, 'negate_$2')
.split(' '), $.trim);
}
function sentiment(phrase) {
var tokens = tokenize(phrase),
score = 0,
words = [],
positive = [],
negative = [];
// Iterate over tokens
var len = tokens.length;
while (len--) {
var obj = tokens[len];
var negate = obj.startsWith('negate_');
if (negate) obj = obj.slice("negate_".length);
if (!afinn.hasOwnProperty(obj)) continue;
var item = afinn[obj];
words.push(obj);
if (negate) item = item * -1.0;
if (item > 0) positive.push(obj);
if (item < 0) negative.push(obj);
score += item;
}
var verdict = score == 0 ? "NEUTRAL" : score < 0 ? "NEGATIVE" : "POSITIVE";
var result = {
verdict: verdict,
score: score,
comparative: score / tokens.length,
positive: [...new Set(positive)],
negative: [...new Set(negative)]
};
return result;
}