我有一个字符串列表,我想在其中筛选包含关键字的字符串.
我想做的事情如下:
fruit = re.compile('apple', 'banana', 'peach', 'plum', 'pinepple', 'kiwi']
Run Code Online (Sandbox Code Playgroud)
所以我可以使用re.search(fruit,list_of_strings)来获取只包含水果的字符串,但我不知道如何使用re.compile列表.有什么建议?(我没有开始使用re.compile,但我认为正则表达式是一种很好的方法.)
And*_*ark 42
您需要将水果列表转换为字符串,apple|banana|peach|plum|pineapple|kiwi以便它是有效的正则表达式,以下内容应该为您执行此操作:
fruit_list = ['apple', 'banana', 'peach', 'plum', 'pineapple', 'kiwi']
fruit = re.compile('|'.join(fruit_list))
Run Code Online (Sandbox Code Playgroud)
编辑:正如评论中指出的ridgerunner,你可能想要在正则表达式中添加单词边界,否则正则表达式将匹配单词,plump因为它们有一个水果作为子字符串.
fruit = re.compile(r'\b(?:%s)\b' % '|'.join(fruit_list))
Run Code Online (Sandbox Code Playgroud)
如你想要完全匹配,真正需要正则表达式...
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!
Run Code Online (Sandbox Code Playgroud)
编辑:如果您需要访问匹配的字符串:
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']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24209 次 |
| 最近记录: |