I'm having problems with my code where I'm trying to add to a new list all words that match a given list (in order at the end to have a basic sentiment analysis code). I have tried passing it through Python Tutor but have had no success. In short, I'm expecting an output of the word great but instead get an empty list.
def remove_punc_and_split (wordlist) :
punc = '.!?/:;,{}' #the punctuation to be removed
no_punc = ""
for char in wordlist :
if char not in punc :
no_punc = no_punc char.lower()
new_word_list = no_punc.split() #dividing the words into seperate strings in a list
return new_word_list
def sentiment1 (wordlist1):
positive_words = ["good","awesome","excellent","great"]
wordlist1 = remove_punc_and_split (comment_1)
pos_word_list = []
for postive_words in wordlist1 :
if wordlist1[0] == positive_words :
pos_word_list.append(wordlist1)
print(wordlist1)
return pos_word_list
comment_1 = 'Good for the price, but poor Bluetooth connections.'
sentiment1(comment_1)
CodePudding user response:
One approach can be to use set.intersection
method for this to find common values between positive_words
and the input list. I also updated it to pass the lowercased sentence wordlist1.lower()
to the remove punc function, because you want to do a case-insensitive match against positive_words
; so first you will need to lowercase all characters in the sentence before you can check if there are any positive words.
def sentiment1(wordlist1):
positive_words = {"good", "awesome", "excellent", "great"}
wordlist1 = remove_punc_and_split(wordlist1.lower())
pos_word_list = list(positive_words.intersection(wordlist1))
return pos_word_list