How do I remove words from a List in a case-insensitive manner?

后端 未结 1 2037
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 18:50

I have a list called words containing words which may be in upper or lower case, or some combination of them. Then I have another list called stopwords

相关标签:
1条回答
  • 2021-01-19 19:10

    Make your word lowercase so you don't need to worry about casing:

    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']
    

    As an additional note, per @cricket_007 (and thanks to @chepner for the correction) comment, making stopwords a set would make it more performant. Notice the change to stopwords above making it a set instead of a list.

    0 讨论(0)
提交回复
热议问题