我正在为 NLTK 停用词而苦苦挣扎。
这是我的一些代码..有人能告诉我哪里出了问题吗?
from nltk.corpus import stopwords
def removeStopwords( palabras ):
return [ word for word in palabras if word not in stopwords.words('spanish') ]
palabras = ''' my text is here '''
最佳答案
您的问题是字符串的迭代器返回每个字符而不是每个单词。
例如:
>>> palabras = "Buenos dias"
>>> [c for c in palabras]
['B', 'u', 'e', 'n', 'a', 's', ' ', 'd', 'i', 'a', 's']
你需要对每个单词进行迭代和检查,幸运的是split函数已经存在于string module下的python标准库中。 .但是,您处理的是包括标点符号在内的自然语言,您应该看看 here使用 re
模块获得更可靠的答案。
一旦你有了一个单词列表,你应该在比较之前将它们全部小写,然后以你已经显示的方式比较它们。
布埃纳苏尔特。
编辑 1
好的,试试这个代码,它应该适合你。它展示了两种实现方式,它们本质上是相同的,但第一种更清晰一些,而第二种更符合 Python 风格。
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
希望对你有帮助
关于python - 摆脱停用词和标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5541745/