首页 > 解决方案 > 正则表达式搜索嵌套字典并在第一次匹配时停止(python)

问题描述

我正在使用嵌套字典,其中包含各种脊椎动物类型。我目前可以阅读嵌套字典并在一个简单的句子中搜索关键字(例如,老虎)。

一旦找到第一个匹配项,我想停止字典搜索(循环)。

我该如何做到这一点?

示例代码:

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))

标签: regexpython-3.xdictionary

解决方案


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'

found = False # Initialized found flag as False (match not found)
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 is not None:
            print (value)
            print (match.group(0))
            found = True # Set found flag as True if you found a match
            break # exit the loop since match is found

    if found: # If match is found then break the loop
        break

推荐阅读