Reputation: 193
Is it possible to iterate through a string of words, classify them as positive, negative, or neutral using sentiment vader, then if they are positive append these positive words to a list? The for loop below is the non working code for what I am trying to accomplish. I am a beginner at Python so would greatly appreciate it if anyone could provide guidance on how to make this work.
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
test_subset=['20170412', 'great', 'bad', 'terrible', 'dog', 'stop', 'good']
test_subset_string_fixed=" ".join(str(x) for x in test_subset)
sid = SentimentIntensityAnalyzer()
pos_word_list=[]
for word in test_subset_string_fixed:
if (sid.polarity_scores(test_subset_string_fixed)).key() == 'pos':
pos_word_list.append(word)
Thank you very much for the help.
Upvotes: 2
Views: 11199
Reputation: 1215
If anyone wants a solution using TextBlob
from textblob import TextBlob
def word_polarity(test_subset):
pos_word_list=[]
neu_word_list=[]
neg_word_list=[]
for word in test_subset:
testimonial = TextBlob(word)
if testimonial.sentiment.polarity >= 0.5:
pos_word_list.append(word)
elif testimonial.sentiment.polarity <= -0.5:
neg_word_list.append(word)
else:
neu_word_list.append(word)
print('Positive :',pos_word_list)
print('Neutral :',neu_word_list)
print('Negative :',neg_word_list)
word_polarity(['20170412', 'great', 'bad', 'terrible', 'dog', 'stop', 'good'])
Output :
('Positive :', ['great', 'good'])
('Neutral :', ['20170412', 'dog', 'stop'])
('Negative :', ['bad', 'terrible'])
Upvotes: 4
Reputation: 5824
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
test_subset=['20170412', 'great', 'bad', 'terrible', 'dog', 'stop', 'good']
sid = SentimentIntensityAnalyzer()
pos_word_list=[]
neu_word_list=[]
neg_word_list=[]
for word in test_subset:
if (sid.polarity_scores(word)['compound']) >= 0.5:
pos_word_list.append(word)
elif (sid.polarity_scores(word)['compound']) <= -0.5:
neg_word_list.append(word)
else:
neu_word_list.append(word)
print('Positive :',pos_word_list)
print('Neutral :',neu_word_list)
print('Negative :',neg_word_list)
Output:
Positive : ['great']
Neutral : ['20170412', 'terrible', 'dog', 'stop', 'good']
Negative : ['bad']
Upvotes: 6