【问题标题】:Issue with stopword removal function停用词删除功能的问题
【发布时间】:2021-08-14 20:51:32
【问题描述】:

我一直在构建一个停用词删除功能,但我不确定自己做错了什么。问题是它返回的是单个字符而不是单词:

from nltk.corpus import stopwords 

stop_words = set(stopwords.words('english')) 

def remove_stop_words(list):
  no_stop_list = []
  for sentence in files:
    for word in sentence:
      no_stops = [word for word in sentence if str(word) not in stop_words]
      no_stop_list.append(no_stops)
  return no_stop_list

no_stops = remove_stop_words(processed_text)
print(no_stops)

根据我的阅读,这似乎应该有效。我有一个列表,其中包含标记的句子,并且在这些标记的句子中是标记的单词。在这个函数中,我的目标是创建一个新列表,遍历列表中的句子,然后遍历句子中的单词,检查它们是否不是停用词,并在新列表中附加非停用词标记。尽管感觉这很合乎逻辑,但它仍然不起作用。

为澄清起见,processed_text 只是一个变量,其中包含已规范化的文本(删除了新换行符、删除了标点符号等)

【问题讨论】:

  • 不工作?你能再描述一下吗?
  • 不应将内置函数用作变量名。请为list选择其他名称。
  • 什么是processed_text?能提供一个简单的demo吗?
  • 假设processed_text 是一个包含句子的列表,你需要sentence.split(" ") 才能得到word
  • @Ghoti:OP 说该列表是标记化的句子。所以他们已经分裂了。

标签: python nlp nltk


【解决方案1】:

你可以试试这个:

def remove_stop_words(sentence_list):
    no_stops = [word for sentence in sentence_list for word in sentence  if str(word) not in stop_words]
    return no_stops

【讨论】:

  • 假设sentence_list是一个“句子”列表,每个“句子”是一个单词列表,则不需要for循环。列表推导执行所有需要的迭代。
  • 你是对的,但如果没有 for 循环,该函数无法识别“句子”
  • 句子是单词列表吗?如果它是一个字符串,那么您需要将其拆分为单词,例如在@Ghoti 的回答中完成的方式。
  • 句子是一个标记词列表。
  • 我刚刚意识到我在函数中的迭代顺序错误。现在已经修复了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 2012-02-28
  • 1970-01-01
  • 2020-11-09
  • 2019-11-07
  • 2019-09-01
  • 1970-01-01
相关资源
最近更新 更多