Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python删除停止字_Python_Stop Words - Fatal编程技术网

用Python删除停止字

用Python删除停止字,python,stop-words,Python,Stop Words,我不明白为什么这个代码不起作用。当我单击run时,它会显示“stopwords删除后:无”。有人能帮助解决这个问题吗?非常感谢 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",las

我不明白为什么这个代码不起作用。当我单击run时,它会显示“stopwords删除后:无”。有人能帮助解决这个问题吗?非常感谢

 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
该函数就地修改列表并返回
None

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

对于您试图执行的操作,您可能希望删除
stop\u 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()
执行此操作的方法:


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

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

检查:我已经编辑了我的答案,并建议了一种替代方法,如果您仍然想使用
remove()
可以,但您需要将
remove()
调用放在try/except块内的一个循环中,以确保每个单词的所有出现都被删除。非常感谢F.J.。它现在可以正常工作了。但是,现在我需要取消拆分函数。我该怎么做?我的意思是我删除了stopwords,并希望不以数组形式打印列表。使用
'.join(last)
,这将返回一个字符串,并在
last
中的每个元素之间添加空格。
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