我正在为 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 '''
我正在为 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 函数已经存在于 python 标准库中的string 模块下。但是,您正在处理包括标点符号在内的自然语言,您应该在这里寻找使用该re
模块的更强大的答案。
一旦你有了一个单词列表,你应该在比较之前将它们全部小写,然后以你已经显示的方式比较它们。
布埃纳苏尔特。
好的,试试这个代码,它应该适合你。它展示了两种方法,它们本质上是相同的,但第一种更清晰,而第二种更 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
我希望这可以帮助你。
首先使用标记器将标记列表(符号)与停止列表进行比较,因此您不需要 re 模块。我添加了一个额外的参数以便在语言之间切换。
def remove_stopwords(sentence, language):
return [ token for token in nltk.word_tokenize(sentence) if token.lower() not in stopwords.words(language) ]
一角钱的网站;)
具有更现代模块的另一种选择(2020 年)
from nltk.corpus import stopwords
from textblob import TextBlob
def removeStopwords( texto):
blob = TextBlob(texto).words
outputlist = [word for word in blob if word not in stopwords.words('spanish')]
return(' '.join(word for word in outputlist))