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