NLP: Score sentiment with a lexicon

Score sentences with a sentiment lexicon, the simplest sentiment analyser.

What to build

A program that sums lexicon scores for each sentence and labels it.

Requirements

  • The lexicon lines are word score with integer scores. Lowercase each word of a sentence and strip . , ! ? from its ends before looking it up; unknown words score 0.
  • For each sentence print the total score and positive, negative or neutral.

Input

Line 1: k. Then k lexicon lines. Then m and m sentences.

Output

m lines.

Constraints

k ≤ 1,000; m ≤ 100.

Example

Input:

3
good 2
bad -2
great 3
2
Good food, great service!
Bad coffee.

Output:

5 positive
-2 negative

Why it works

Each known word contributes its sentiment and unknown words contribute nothing, so the sign of the sum says which kind of words dominate the sentence.

Examples

Example 1 · Input
3
good 2
bad -2
great 3
2
Good food, great service!
Bad coffee.
Expected output
5 positive
-2 negative
Example 2 · Input
2
love 3
hate -3
1
I love it but I hate the price
Expected output
0 neutral

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Clean each word with `w.strip(".,!?").lower()` and add `lexicon.get(word, 0)`.

Hint 2

The label is positive for a score above 0, negative below 0 and neutral at exactly 0.

Solution

Show one correct solution (try it yourself first)
lexicon = {}
for _ in range(int(input())):
    word, value = input().split()
    lexicon[word] = int(value)
for _ in range(int(input())):
    words = [w.strip(".,!?").lower() for w in input().split()]
    score = sum(lexicon.get(w, 0) for w in words)
    label = "positive" if score > 0 else "negative" if score < 0 else "neutral"
    print(score, label)

Lesson: Sentiment analysis →