v9.1.1
Menu

Sentiment Word Counter

easyFREEText ClassificationNLP 2: Applications

Given a text and two lists of words (positive and negative), count how many positive and negative words appear in the text and determine the overall sentiment.

Function: sentiment_count(pos, neg, text)

  • pos: list of positive words
  • neg: list of negative words
  • text: the text to analyze (words separated by spaces)

Output: Return the string "positive X negative Y LABEL" where X and Y are counts (every occurrence of a word in the text counts), and LABEL is "positive" if X > Y, "negative" if Y > X, or "neutral" if equal.

All matching is case-insensitive.

Example

Input
good,great,happy
bad,sad,terrible
I feel good and great today
Output
positive 2 negative 0 positive
Reasoning
  • Inputs: pos is the positive vocabulary {good, great, happy}, neg is the negative vocabulary {bad, sad, terrible}, and text is the sentence I feel good and great today.
  • Case is ignored, so the sentence becomes the six words: i, feel, good, and, great, today. Each word is checked against both vocabularies.
  • Positive hits: good ✓ and great ✓, so X=2X = 2. The word happy never appears, which simply contributes nothing.
  • Negative hits: none of bad, sad or terrible occurs, so Y=0Y = 0.
  • Label: since X>YX > Y (2>02 > 0), the sentiment is positive, giving positive 2 negative 0 positive.
  • Notice that the word "positive" appears twice in the output for different reasons: once as a fixed tag before the count, once as the label. Every occurrence counts, so "Good good BAD" would score X=2X = 2, Y=1Y = 1; and when X=YX = Y (including 0=00 = 0) the label is neutral.

Constraints

  • Case-insensitive matching
  • Words compared after lowercasing
  • Output format: "positive X negative Y LABEL"

Learn this in

More from NLP 2: Applications

solution.py

Test results

Sign in to run your code against the test cases.