how to do re.compile() with a list in python

前端 未结 5 583
日久生厌
日久生厌 2020-12-04 20:08

I have a list of strings in which I want to filter for strings that contains keywords.

I want to do something like:

fruit = re.compile(\'apple\', \'         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 21:01

    As you want exact matches, no real need for regex imo...

    fruits = ['apple', 'cherry']
    sentences = ['green apple', 'yellow car', 'red cherry']
    for s in sentences:
        if any(f in s for f in fruits):
            print s, 'contains a fruit!'
    # green apple contains a fruit!
    # red cherry contains a fruit!
    

    EDIT: If you need access to the strings that matched:

    from itertools import compress
    
    fruits = ['apple', 'banana', 'cherry']
    s = 'green apple and red cherry'
    
    list(compress(fruits, (f in s for f in fruits)))
    # ['apple', 'cherry']
    

提交回复
热议问题