Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/natural/sentiment/SentimentAnalyzer.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ class SentimentAnalyzer {

// words is an array of words (strings)
getSentiment (words) {
if (words.length === 0) {
return 0
}

let score = 0
let negator = 1
let nrHits = 0
Expand Down
27 changes: 27 additions & 0 deletions spec/SentimentAnalyzer_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ THE SOFTWARE.

import {
SentimentAnalyzer as Analyzer,
WordTokenizer,
PorterStemmer,
PorterStemmerPt,
PorterStemmerNl,
Expand Down Expand Up @@ -223,3 +224,29 @@ describe('The sentiment analyzer analyzes the sentiment of sentences in multiple
})
})
})

describe('The sentiment analyzer handles empty input', function () {
for (const vocabularyType of ['afinn', 'afinnFinancialMarketNews', 'senticon', 'pattern']) {
it('returns a neutral score for an empty array with ' + vocabularyType, function () {
const analyzer = new Analyzer('English', undefined, vocabularyType)

expect(analyzer.getSentiment([])).toBe(0)
})
}

it('returns a neutral score for an empty array when a stemmer is supplied', function () {
const analyzer = new Analyzer('English', PorterStemmer, 'afinn')

expect(analyzer.getSentiment([])).toBe(0)
})

for (const text of ['', ' \t\n ', '...!?']) {
it('returns a neutral score for tokenized text ' + JSON.stringify(text), function () {
const analyzer = new Analyzer('English', PorterStemmer, 'afinn')
const tokens = new WordTokenizer().tokenize(text)

expect(tokens).toEqual([])
expect(analyzer.getSentiment(tokens)).toBe(0)
})
}
})