Make a lexicon scorer understand "not good" and "very bad".
What to build
A program that scores sentences with a lexicon, intensifiers and negation.
Requirements
- Clean words as in the easy exercise (lowercase, strip
. , ! ?). For each lexicon word at position i: if the word just before it is a booster, multiply its score by the booster's factor; then, if any negation word is among the three words before it, flip the sign. - For each sentence print the total with one decimal place and
positive,negativeorneutral.
Input
Line 1: k, then k lines word score. Next line: the negation words. Next: b, then b lines word factor. Then m and m sentences.
Output
m lines.
Constraints
k ≤ 1,000; m ≤ 100.
Example
Input:
3
good 2
bad -2
boring -2
not never
2
very 1.5
slightly 0.5
3
Not good at all.
The plot was never boring
A very bad, slightly boring film.
Output:
-2.0 negative
2.0 positive
-4.0 negative
Why it works
A booster changes how strong the next sentiment word is, and a negation shortly before a sentiment word reverses it, which fixes the most common errors of a plain word sum.
Examples
3 good 2 bad -2 boring -2 not never 2 very 1.5 slightly 0.5 3 Not good at all. The plot was never boring A very bad, slightly boring film.
-2.0 negative 2.0 positive -4.0 negative
1 like 2 not 1 really 2 2 I do not really like it I really like it
-4.0 negative 4.0 positive
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For the word at position i, the booster is `words[i - 1]` (when i > 0) and the negation window is `words[max(0, i - 3):i]`.
Hint 2
Apply the booster factor first, then flip the sign if a negation word is in the window.
Solution
Show one correct solution (try it yourself first)
lexicon = {}
for _ in range(int(input())):
word, value = input().split()
lexicon[word] = float(value)
negations = input().split()
boosters = {}
for _ in range(int(input())):
word, factor = input().split()
boosters[word] = float(factor)
for _ in range(int(input())):
words = [w.strip(".,!?").lower() for w in input().split()]
score = 0.0
for i, w in enumerate(words):
if w not in lexicon:
continue
value = lexicon[w]
if i > 0 and words[i - 1] in boosters:
value *= boosters[words[i - 1]]
if any(n in words[max(0, i - 3):i] for n in negations):
value = -value
score += value
label = "positive" if score > 0 else "negative" if score < 0 else "neutral"
print(f"{score:.1f} {label}")