v9.1.1
Menu

Sentiment Scorer

easyPROText ClassificationNLP 2: Applications

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

Input
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
Output
0.25
Reasoning
  • Inputs: lexicon assigns a score to 5 words (good =1.0=1.0, great =1.5=1.5, bad =−1.0=-1.0, terrible =−2.0=-2.0, ok =0.0=0.0), and text is a lowercase sentence of 9 space-separated words.
  • Matching: reading the sentence word by word, only great and bad have 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 s1=1.5s_1 = 1.5 and s2=−1.0s_2 = -1.0, the result is 1n∑isi=1.5+(−1.0)2=0.52=0.25\frac{1}{n}\sum_i s_i = \frac{1.5 + (-1.0)}{2} = \frac{0.5}{2} = 0.25.
  • 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 (22), not the sentence length (99). Dividing by 9 would give about 0.05560.0556. A repeated lexicon word counts once per occurrence, and if nothing matches the answer is 0.00.0.

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

Learn this in

More from NLP 2: Applications

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.