【问题标题】:Removing Stopwords in Python在 Python 中删除停用词
【发布时间】:2013-12-17 09:32:34
【问题描述】:

我正在尝试使用.join 函数从用户输入字符串中删除停用词。它看起来像这样:

while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    remove_stopwords = ''.join(word for word in line.split() if word not in stop_words)

我在顶部的列表中定义了stop_words。问题是,当我输入要删除的停用词的字符串时,它只会删除第一个单词并留下其余单词。任何帮助都会很棒。我是新手,所以这可能很愚蠢。

【问题讨论】:

  • stopword 声明在哪里?
  • 哦,这也是在显示的代码上方声明的。当输入仅包含句号的行时,它被设置为中断。

标签: python python-2.7 stop-words


【解决方案1】:

这是使用filter 函数的单行代码:

" ".join(filter(lambda word: word not in stop_words, line.split()))

此外,考虑将停用词存储在set 而不是list。搜索操作的平均算法复杂度 (in) 对于 set 是恒定的,对于 list 是线性的。

编辑:您的程序似乎按预期工作,join 字符串有一个额外的空间。这是有道理的,因为(x for x in y if f(x)) 大致相当于filter

  stop_words = set(["hi", "bye"])
  stopword = "DONE"
  while True:
      line = raw_input()
      if line.strip() == stopword:
          break
      print(" ".join(word for word in line.split() if word not in stop_words))

输入:

hello hi my name is bye justin

输出:

hello my name is justin

您的错误必须在程序中的其他位置。你还在做什么?

【讨论】:

  • 谢谢,这有帮助。从列表切换到集合似乎有助于解决问题。
猜你喜欢
  • 1970-01-01
  • 2018-02-25
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多