Python 如果字符串包含stopwords,请从字符串中删除元素

Python 如果字符串包含stopwords,请从字符串中删除元素,python,python-3.x,nltk,Python,Python 3.x,Nltk,我的清单如下: lst = ['for Sam', 'Just in', 'Mark Rich'] 我正在尝试从字符串列表(字符串包含一个或多个单词)中删除包含stopwords的元素 由于列表中的第一个和第二个元素包含的和中的,它们是停止字,它将返回 new_lst = ['Mark Rich'] 我尝试的 from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) lst = ['fo

我的清单如下:

lst = ['for Sam', 'Just in', 'Mark Rich']
我正在尝试从字符串列表(字符串包含一个或多个单词)中删除包含
stopwords
的元素

由于列表中的第一个和第二个元素包含的
中的
,它们是
停止字
,它将返回

new_lst = ['Mark Rich'] 
我尝试的

from nltk.corpus import stopwords

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

lst = ['for Sam', 'Just in', 'Mark Rich']
new_lst = [i.split(" ") for i in lst]
new_lst = [" ".join(i) for i in new_lst for j in i if j not in stop_words]
这给我的输出是:

['for Sam', 'Just in', 'Mark Rich', 'Mark Rich']

您需要一个
if
语句,而不是额外的嵌套:

new_lst = [' '.join(i) for i in new_lst if not any(j in i for j in stop_words)]
如果您希望利用
设置
,可以使用:


下面是一个演示:

stop_words = {'for', 'in'}

lst = ['for Sam', 'Just in', 'Mark Rich']
new_lst = [i.split() for i in lst]
new_lst = [' '.join(i) for i in new_lst if stop_words.isdisjoint(i)]

print(new_lst)

# ['Mark Rich']

您可以使用列表理解和使用
集合
检查两个列表中的任何单词是否相交:

[i for i in lst if not set(stop_words) & set(i.split(' '))]
['Mark Rich']]

你的第一个答案很有魅力,但第二个答案给出的是一个空列表。@反社会者,不,很好,请看我的例子。谢谢。工作得很有魅力。只有一件事,在你的回答中你把
]
放错了位置。注意
集合。交叉
集合更复杂。不相交
。没有必要计算两组的确切交集来确定交集是否为空。是的,当我看到你的答案时,我确实想到了
.isdisjoint
。澄清用thx
[i for i in lst if not set(stop_words) & set(i.split(' '))]
['Mark Rich']]