簡體   English   中英

如何使用 python 中的列表執行 re.compile()

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

我有一個字符串列表,我想在其中過濾包含關鍵字的字符串。

我想做類似的事情:

fruit = re.compile('apple', 'banana', 'peach', 'plum', 'pinepple', 'kiwi']

所以我可以使用 re.search(fruit, list_of_strings) 只獲取包含水果的字符串,但我不確定如何使用 re.compile 的列表。 有什么建議么? (我不打算使用 re.compile,但我認為正則表達式會是一個很好的方法。)

您需要將水果列表轉換為字符串apple|banana|peach|plum|pineapple|kiwi以便它是有效的正則表達式,以下應該為您執行此操作:

fruit_list = ['apple', 'banana', 'peach', 'plum', 'pineapple', 'kiwi']
fruit = re.compile('|'.join(fruit_list))

編輯:正如 ridgerunner 在評論中指出的那樣,您可能希望在正則表達式中添加單詞邊界,否則正則表達式將匹配像plump這樣的單詞,因為它們有一個水果作為 substring。

fruit = re.compile(r'\b(?:%s)\b' % '|'.join(fruit_list))

因為你想要完全匹配,所以不需要正則表達式 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!

編輯:如果您需要訪問匹配的字符串:

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

Pyhton 3.x 更新:

fruit_list = ['apple', 'banana', 'peach', 'plum', 'pineapple', 'kiwi']
fruit = re.compile(r'\b(?:{0})\b'.format('|'.join(fruit_list))

您可以創建一個正則表達式,當找到任何術語時,它將匹配:

>>> s, t = "A kiwi, please.", "Strawberry anyone?"
>>> import re
>>> pattern = re.compile('apple|banana|peach|plum|pineapple|kiwi', re.IGNORECASE)
>>> pattern.search(s)
<_sre.SRE_Match object at 0x10046d4a8>
>>> pattern.search(t) # won't find anything

代碼:

fruits =  ['apple', 'banana', 'peach', 'plum', 'pinepple', 'kiwi'] 
fruit_re = [re.compile(fruit) for fruit in fruits]
fruit_test = lambda x: any([pattern.search(x) for pattern in fruit_re])

示例用法:

fruits_veggies = ['this is an apple', 'this is a tomato']
return [fruit_test(str) for str in fruits_veggies]

編輯:我意識到安德魯的解決方案更好。 您可以使用 Andrew 的正則表達式改進fruit_test

fruit_test = lambda x: andrew_re.search(x) is None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM