【问题标题】:Remove Stop Words in Python List Using List Comprehension使用列表理解删除 Python 列表中的停用词
【发布时间】:2021-04-23 02:24:48
【问题描述】:

对于简单的问题,Python 新手非常抱歉,但我找不到适合我情况的确切解决方案。

我有一个 python 列表,我想从列表中删除停用词。如果它与另一个令牌配对,我的代码不会删除停用词。

    from nltk.corpus import stopwords
    rawData = ['for', 'the', 'game', 'the movie']
    text = [each_string.lower() for each_string in rawData]
    newText = [word for word in text if word not in stopwords.words('english')]
    print(newText)

当前输出: ['游戏','电影']

期望的输出 ['游戏','电影']

我更愿意为此使用列表推导。

【问题讨论】:

  • 正确。它不会产生“电影”。它目前产生“电影”。因此我的评论是“电影”是所需的输出。
  • 如果您要在诸如“电影”之类的短语中测试诸如“the”之类的停用词,那么您应该将短语拆分为 ['the', 'movie'] 并测试每个短语中的单词。针对单个停用词测试短语本身是行不通的。
  • 谢谢。我该怎么做?
  • 您可以使用[word for phrase in text for word in phrase.split()] 获取单个单词的列表,这将产生['for', 'the', 'game', 'the', 'movie'],然后使用您的第二个列表理解来删除停用词。

标签: python list nlp nltk stop-words


【解决方案1】:

我花了一段时间才做到这一点,因为列表推导不是我的事。不管怎样,我就是这样做的:

import functools

stopwords = ["for", "the"]

rawData = ['for', 'the', 'game', 'the movie']
lst = functools.reduce(lambda x,y: x+y, [i.split() for i in rawData])
newText = [word for word in lst if word not in stopwords]
print(newText)

基本上,第 4 行将列表值拆分为嵌套列表并将嵌套列表转换为一维。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2019-09-10
    • 2018-09-28
    • 2016-09-25
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多