为什么我的新列表输出一个空的,而我应该得到一个答案



我的代码遇到了问题,我试图将与给定列表匹配的所有单词添加到新列表(按顺序在最后有一个基本的情感分析代码)。我试过通过Python教程,但没有成功。简而言之,我期望输出单词great而是得到一个空列表.

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)

一种方法是使用set.intersection方法来查找positive_words和输入列表之间的公共值。我还更新了它,将小写句子wordlist1.lower()传递给删除标点函数,因为您想对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

最新更新