我有一个名为words
包含可能为大写或小写或它们的某种组合的单词。然后我有另一个列表称为stopwords
其中仅包含小写单词。现在我想浏览一下其中的每个单词stopwords
并从中删除该单词的所有实例words
以不区分大小写的方式,但我不知道该怎么做。建议?
Example:
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])
Outputs:
['is', 'a', 'string']
作为补充说明,根据 @cricket_007(并感谢 @chepner 的更正)评论,将停用词设置为一组将使其性能更高。请注意上面对停用词的更改,使其成为一个集合而不是列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)