【问题标题】:Get rid of stopwords and punctuation摆脱停用词和标点符号
【发布时间】:2011-07-29 08:15:07
【问题描述】:

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

【问题讨论】:

  • 你只是错过了对函数的调用吗?尝试在最后一行之后添加print removeStopwords(palabras)
  • 对!!!我错过了!
  • 确保接受一个答案并点赞
  • 我不知道您是否遇到过 stopwords.words('spanish') 返回一个列表,其中并非每个单词都使用 Unicode 编码的问题。因此,检查一个单词是否存在于用 Unicode (u'word') 编码的单词中,并使用 'in' 运算符,可能会导致错误的比较。我收到这条消息:UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - 将它们解释为不相等有什么线索吗?我猜 NLTK.CORPUS.STOPWORDS 应该返回 unicode 列表 gracias!

标签: python nltk stop-words


【解决方案1】:

您的问题是字符串的迭代器返回每个字符而不是每个单词。

例如:

>>> 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

好的,试试这个代码,它应该适合你。它展示了两种方法,它们本质上是相同的,但第一种更清晰,而第二种更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 

希望对你有帮助。

【讨论】:

  • 我们使用“Buena suerte”。 re 模块帮助我使用标点符号,但我仍在尝试将它与停用词功能结合起来
  • 把停用词变成一个集合,它会快很多
  • 如果他们已经在使用 nltk 为什么不使用 Tokenizer 并用三行解决它?
【解决方案2】:

首先使用标记器将标记列表(符号)与停止列表进行比较,因此您不需要 re 模块。我添加了一个额外的参数以便在语言之间切换。

def remove_stopwords(sentence, language):
    return [ token for token in nltk.word_tokenize(sentence) if token.lower() not in stopwords.words(language) ]

Dime 网站 ;)

【讨论】:

    【解决方案3】:

    具有更现代模块的另一种选择 (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))
    

    【讨论】:

      猜你喜欢
      • 2020-04-02
      • 2013-06-27
      • 2011-10-02
      • 2018-09-06
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多