I have to count the times positive and negative words appear in a passage.
I have a list of positive words, list of negative words, and a passage excerpt.
pos_words = ['happy', 'like', 'love', 'good', 'favorite', 'best', 'great', 'amazing', 'joyful', 'positive']
neg_words = ['sad', 'dislike', 'hate', 'angry', 'horrible', 'bad', 'worst', 'boring', 'negative']
passage_excerpt = "I love CSS 1, it's my favorite class and not as horrible as I thought"
I have to return a dictionary titled sentiment_info that looks like this:
{'num_pos_words': ..., # how many positive words
'num_neg_words': ..., # how many negative words
'num_words_total': ... # how many total words
I have tried this code so far:
def calculate_words(x):
cleaned_passage = clean_text(x)
num_pos_words = 0
num_neg_words = 0
num_words_total = 0
if x in pos_words and passage_excerpt:
num_pos_words += 1
if x in neg_words and passage_excerpt:
num_neg_words += 1
num_words_total = num_pos_words + num_neg_words
return{'num_pos_words': num_pos_words,
'num_neg_words': num_neg_words,
'num_words_total': num_words_total}
I do not know if a function was the correct approach or I needed a for loop.
I little modification in your code:
def calculate_words(y):
num_pos_words = 0
num_neg_words = 0
num_words_total = 0
for x in y.split(): # ['I', 'love', 'CSS', '1,', "it's", 'my', 'favorite', 'class', 'and', 'not', 'as', 'horrible', 'as', 'I', 'thought']
if x in pos_words and x in passage_excerpt:
num_pos_words += 1
if x in neg_words and x in passage_excerpt:
num_neg_words += 1
num_words_total = num_pos_words + num_neg_words
return{'num_pos_words': num_pos_words,
'num_neg_words': num_neg_words,
'num_words_total': num_words_total}
print(calculate_words(passage_excerpt))
#{'num_pos_words': 2, 'num_neg_words': 1, 'num_words_total': 3}