我有一个名为 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/