python - 摆脱停用词和标点符号

标签 python nltk stop-words

我正在为 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/

相关文章:

python - 按出现次数对二元组进行排序 NLTK

mysql - 如何从内容不包含辅助表中存在的停用词的表中选择所有帖子

python - 使用NLTK的编码问题

python,多线程,在公共(public)文件上使用 pandas "to_csv"安全吗?

python - 有没有办法检查python中两个完整句子之间的相似性?

python - 在 Eclipse 中配置 Pydev 解释器以使用 Enthought Python Distribution

python - 现在删除的模块 'nltk.model.NGramModel' 是否有替代品?

r - 寻找推特和短信风格的停用词

python - 训练 TensorFlow 预测总和

python - pycharm上pytorch 1.6.0安装问题