Sentiment Scorer
Score the sentiment of text using a simple lexicon-based approach.
Given a sentiment lexicon (mapping words to scores) and a text, compute the average sentiment score of all lexicon words found in the text.
Function arguments:
- lexicon: a dictionary mapping each word to its sentiment score (float)
- text: the text to score (lowercase words separated by spaces)
Output: Average sentiment score of matched words, rounded to 4 decimal places. If no lexicon words are found, return 0.0.
Example
5 good 1.0 great 1.5 bad -1.0 terrible -2.0 ok 0.0 the movie was great but the ending was bad
0.25
- Inputs:
lexiconassigns a score to 5 words (good,great,bad,terrible,ok), andtextis a lowercase sentence of 9 space-separated words. - Matching: reading the sentence word by word, only
greatandbadhave a score. The other 7 words (the, movie, was, but, ending, and the repeats) carry no sentiment and are ignored entirely: they do not count as zeros. - Averaging: with matched scores and , the result is .
- Output:
0.25, a single float rounded to 4 decimal places. A positive and a negative word partly cancel, leaving a mildly positive score. - Notice that the denominator is the number of matched words (), not the sentence length (). Dividing by 9 would give about . A repeated lexicon word counts once per occurrence, and if nothing matches the answer is .
Constraints
- Sentiment scores can be negative (negative sentiment) or positive
- Only average over words found in the lexicon
- If a word appears multiple times in text, count it each time
- If no lexicon words found, return 0.0
- Round to 4 decimal places