删除列表中的所有特定单词

2024-06-09 21:15:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的列表['land_transport', 'and', 'or', 'port', 'of', 'surveyor', 'and', 'organization']。我想删除所有单词:andorof。一、 因此,提出以下代码块

my_list = ['land_transport', 'and', 'or', 'port', 'of', 'surveyor', 'and', 'organization']
print('Before: {}'.format(my_list))
my_list = list(filter(lambda a: 'and' not in a and 'of' not in a and 'or' not in a, my_list))
print('After: {}'.format(my_list))

但是,我的代码给出如下输出

Before: ['land_transport', 'and', 'or', 'port', 'of', 'surveyor', 'and', 'organization']
After: []

我想要的应该是

['land_transport', 'port', 'surveyor', 'organization']

当然,有几种方法。但是我想坚持使用lambda函数来解决这个问题。对我的问题有什么建议吗?你知道吗


Tags: orandof代码inportmynot
3条回答

虽然以上的答案符合需要,但我认为你打算删除停止语。你知道吗

nltk是Python中最好的资源。你可以使用nltk.corpus.stopwords

你不必做太多的操作,如果你知道你正在删除实际的英语停止词。你知道吗

from nltk.corpus import stopwords
word_list = ['land_transport', 'and', 'or', 'port', 'of', 'surveyor', 'and', 'organization']
filtered_words = [word for word in word_list if word not in stopwords.words('english')]

print(filtered_words)

['land_transport', 'port', 'surveyor', 'organization']

沃拉

您的筛选不正确,请使用:

filter_set = {'and', 'or', 'of'}
my_list = list(filter(lambda a: a not in filter_set, my_list))

如果需要my_list中所有不在filter_set中的项,请注意使用set,它将使查找更快(O(N) vs O(1))。你知道吗

您可以创建一个新列表,存储要筛选的所有单词:

my_list = ['land_transport', 'and', 'or', 'port', 'of', 'surveyor', 'and', 'organization']
to_remove = ['or', 'of', 'and']
new_list = list(filter(lambda x:x not in to_remove, my_list))

输出:

['land_transport', 'port', 'surveyor', 'organization']

相关问题 更多 >