【发布时间】:2018-10-13 20:42:25
【问题描述】:
我使用的是嵌套字典,其中包含各种脊椎动物类型。我目前可以阅读嵌套字典并在一个简单的句子中搜索关键字(例如,老虎)。
一旦找到第一个匹配项,我想停止字典搜索(循环)。
我该如何做到这一点?
示例代码:
vertebrates = {'dict1':{'frog':'amphibian', 'toad':'amphibian', 'salamander':'amphibian','newt':'amphibian'},
'dict2':{'bear':'mammal','cheetah':'mammal','fox':'mammal', 'mongoose':'mammal','tiger':'mammal'},
'dict3': {'anteater': 'mammal', 'tiger': 'mammal'}}
sentence = 'I am a tiger'
for dictionaries, values in vertebrates.items():
for pattern, value in values.items():
animal = re.compile(r'\b{}\b'.format(pattern), re.IGNORECASE|re.MULTILINE)
match = re.search(animal, sentence)
if match:
print (value)
print (match.group(0))
【问题讨论】:
标签: regex python-3.x dictionary