【问题标题】:Stopwords Removal with Python使用 Python 去除停用词
【发布时间】:2014-05-20 09:43:51
【问题描述】:

我不明白为什么这段代码不起作用。当我单击运行时,它显示“删除停用词后:无”。任何人都可以帮助解决问题吗?非常感谢。

 stop_words = ["the", "of", "a", "to", "be", "from", "or"]
 last = lower_words.split()

 for i in stop_words:
     lastone = last.remove(i)
     print "\nAAfter stopwords removal:\n",lastone

【问题讨论】:

标签: python stop-words


【解决方案1】:

list.remove() 函数在原地修改列表并返回None

所以当您执行last.remove(i) 时,它会从last 列表中删除i 的第一次出现并返回None,因此lastone 将始终设置为None

对于您要执行的操作,您可能希望删除所有出现在 stop_words 中的项目,因此 last.remove() 将不是最有效的方法。相反,我会使用列表理解执行以下操作:

stop_words = set(["the", "of", "a", "to", "be", "from", "or"])
last = lower_words.split()
last = [word for word in last if word not in stop_words]

stop_words 转换为集合可以提高效率,但如果将其保留为列表,则会得到相同的行为。

为了完整起见,以下是您需要使用remove() 执行此操作的方法:

stop_words = ["the", "of", "a", "to", "be", "from", "or"]
last = lower_words.split()
for word in stop_words:
    try:
        while True:
            last.remove(word)
    except ValueError:
        pass

【讨论】:

  • 我已经编辑了我的答案,并提出了一种替代方法的建议,如果您仍然想使用remove(),您可以,但您需要将remove() 调用放在在 try/except 块内循环以确保删除所有出现的每个单词。
  • 非常感谢 F.J.。它现在可以正常工作了。但是,现在我需要取消拆分功能。我怎样才能做到这一点 ?我的意思是我删除了停用词,并且不想将列表打印为数组。
  • 使用' '.join(last),这将返回一个字符串,在last中的每个元素之间添加一个空格。
【解决方案2】:

这是一个接收文本并返回不带停用词的文本的函数。它通过忽略字典停用词中的每个单词来实现其目标。我对每个单词 i 使用 .lower() 函数,因为大多数停用词包都是小写字母,但我们的文本可能不是。

def cut_stop_words(text,stopwords):
  new_text= ''
  for i in text.split():

    if (i.lower()) in stopwords:
         pass
     else:
         new_text= new_text.strip() + ' ' + i

  return new_text

【讨论】:

    猜你喜欢
    • 2019-01-25
    • 2015-09-05
    • 2017-01-21
    • 2015-09-04
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    相关资源
    最近更新 更多