如何在Python中使用列表进行re.compile()
我有一个字符串的列表,我想从中筛选出包含特定关键词的字符串。
我想做的事情是:
fruit = re.compile('apple', 'banana', 'peach', 'plum', 'pinepple', 'kiwi']
这样我就可以用 re.search(fruit, list_of_strings) 来获取只包含水果的字符串,但我不太确定怎么把列表和 re.compile 一起用。有没有什么建议?(我并不一定要用 re.compile,但我觉得正则表达式可能是个不错的方法。)
5 个回答
2
你可以创建一个正则表达式,这个表达式会在找到任何一个指定的词时匹配成功:
>>> 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
7
因为你想要的是完全匹配,所以我觉得其实不需要用正则表达式...
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']
56
你需要把你的水果列表变成一个字符串,格式是 apple|banana|peach|plum|pineapple|kiwi
,这样才能成为一个有效的正则表达式。下面的代码可以帮你做到这一点:
fruit_list = ['apple', 'banana', 'peach', 'plum', 'pineapple', 'kiwi']
fruit = re.compile('|'.join(fruit_list))
正如ridgerunner在评论中提到的,你可能还想在正则表达式中加上单词边界,不然的话,正则表达式会匹配到像 plump
这样的单词,因为它里面包含了一个水果的名字。
fruit = re.compile(r'\b(?:%s)\b' % '|'.join(fruit_list))
最后,如果你的 fruit_list
中的字符串可能包含特殊字符,你可能需要使用 re.escape
来处理。
'|'.join(map(re.escape, fruit_list))