您的问题是字符串的迭代器返回每个字符而不是每个单词。
例如:
>>> palabras = "Buenos dias"
>>> [c for c in palabras]
['B', 'u', 'e', 'n', 'a', 's', ' ', 'd', 'i', 'a', 's']
你需要迭代并检查每个单词,幸运的是 split 函数已经存在于 python 标准库中字符串模块。但是,您正在处理自然语言,包括标点符号,您应该看看here以获得更可靠的答案,使用re
module.
一旦您有了单词列表,您应该在比较之前将它们全部小写,然后按照您已经显示的方式进行比较。
布埃纳苏尔特。
EDIT 1
好的,试试这个代码,它应该对你有用。它展示了两种方法,它们本质上是相同的,但第一种更清晰,而第二种更Pythonic。
import re
from nltk.corpus import stopwords
scentence = 'El problema del matrimonio es que se acaba todas las noches despues de hacer el amor, y hay que volver a reconstruirlo todas las mananas antes del desayuno.'
#We only want to work with lowercase for the comparisons
scentence = scentence.lower()
#remove punctuation and split into seperate words
words = re.findall(r'\w+', scentence,flags = re.UNICODE | re.LOCALE)
#This is the simple way to remove stop words
important_words=[]
for word in words:
if word not in stopwords.words('spanish'):
important_words.append(word)
print important_words
#This is the more pythonic way
important_words = filter(lambda x: x not in stopwords.words('spanish'), words)
print important_words
我希望这可以帮助你。