Skip to content

Commit

Permalink
Check if type and language exist
Browse files Browse the repository at this point in the history
  • Loading branch information
Hugo-ter-Doest committed Nov 20, 2023
1 parent dcd13a5 commit 14ab3c2
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions lib/natural/sentiment/SentimentAnalyzer.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

'use strict'

const DEBUG = true

// Afinn
const englishAfinnVoca = require('afinn-165')
const spanishAfinnVoca = require('./Spanish/afinnShortSortedSpanish.json')
Expand Down Expand Up @@ -87,6 +89,15 @@ class SentimentAnalyzer {
// this.vocabulary must be a copy of the languageFiles object
// or in subsequent execution the polarity will be undefined
// shallow copy - requires ES6
if (languageFiles[type]) {
if (languageFiles[type][language]) {
if (languageFiles[type][language][0]) {
this.vocabulary = Object.create(languageFiles[type][language][0])
}
}
} else {
throw new Error('Type Language ' + language + ' not supported')
}
this.vocabulary = Object.assign({}, languageFiles[type][language][0])
Object.setPrototypeOf(this.vocabulary, null)
if (type === 'senticon') {
Expand All @@ -98,7 +109,7 @@ class SentimentAnalyzer {
Object.keys(this.vocabulary).forEach(word => {
this.vocabulary[word] = this.vocabulary[word].polarity
})
// console.log(JSON.stringify(this.vocabulary, null, 2));
DEBUG && console.log(JSON.stringify(this.vocabulary, null, 2));
}
}

Expand All @@ -120,32 +131,32 @@ class SentimentAnalyzer {
getSentiment (words) {
let score = 0
let negator = 1
// let nrHits = 0
DEBUG && let nrHits = 0

words.forEach((token) => {
const lowerCased = token.toLowerCase()
if (this.negations.indexOf(lowerCased) > -1) {
negator = -1
// nrHits++
DEBUG && nrHits++
} else {
// First try without stemming
if (this.vocabulary[lowerCased] !== undefined) {
score += negator * this.vocabulary[lowerCased]
// nrHits++
DEBUG && nrHits++
} else {
if (this.stemmer) {
const stemmedWord = this.stemmer.stem(lowerCased)
if (this.vocabulary[stemmedWord] !== undefined) {
score += negator * this.vocabulary[stemmedWord]
// nrHits++
DEBUG && nrHits++
}
}
}
}
})

score = score / words.length
// console.log("Number of hits: " + nrHits);
DEBUG && console.log("Number of hits: " + nrHits);

return score
}
Expand Down

0 comments on commit 14ab3c2

Please sign in to comment.