python - 如何以不区分大小写的方式从列表中删除单词?

标签 python string list

我有一个名为 words 的列表,其中包含可能是大写或小写或它们的某种组合的单词。然后我有另一个名为 stopwords 的列表,它只包含小写单词。现在我想遍历 stopwords 中的每个单词,并以不区分大小写的方式从 words 中删除该单词的所有实例,但我不知道该怎么做.有什么建议吗?

例子:

words = ['This', 'is', 'a', 'test', 'string']
stopwords = ['this', 'test']

for stopword in stopwords:
    if stopword in words:
        words.remove(stopword);

print words

显示的结果是这样的:['This', 'is', 'a', 'string']

正确的返回应该是这样的:['is', 'a', 'string']

最佳答案

让你的单词小写,这样你就不用担心大小写了:

words = ['This', 'is', 'a', 'test', 'string']
stopwords = {'this', 'test'}

print([i for i in words if i.lower() not in stopwords])

输出:

['is', 'a', 'string']

作为附加说明,根据@cricket_007(并感谢@chepner 的更正)评论,将停用词设为一个集合会提高性能。请注意上面停用词的变化,使它成为一个集合而不是一个列表。

关于python - 如何以不区分大小写的方式从列表中删除单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35630691/

相关文章:

python - 如何从另一个进程中杀死一个进程?

Java:如何在反转分割字后将分隔符读回字符串?

c++ - 下层 std::vector<std::string>

python - 在元组列表中查找元素

javascript - 如何获取列表项 Javascript 的值/文本

python - 在 Django Admin 中,您可以根据搜索结果限制过滤器选项吗?

python - 如何在程序中将参数传递给scrapy spider?

Python。相同的字符串以不同的编码出现?

python - 如何交换字符串中的逗号和点

c# - 我应该使用列表吗?