Regex 正则表达式搜索嵌套字典并在第一次匹配时停止(python)

Regex 正则表达式搜索嵌套字典并在第一次匹配时停止(python),regex,python-3.x,dictionary,Regex,Python 3.x,Dictionary,我正在使用一个嵌套字典,其中包含各种脊椎动物类型。我目前可以在中阅读嵌套字典,并在简单的句子中搜索关键字(例如tiger) 一旦找到第一个匹配项,我想停止字典搜索(循环) 我如何做到这一点 示例代码: vertebrates = {'dict1':{'frog':'amphibian', 'toad':'amphibian', 'salamander':'amphibian','newt':'amphibian'}, 'dict2':{'bear':'mammal','ch

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

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

我如何做到这一点

示例代码:

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

我的生产代码从文件中读取行以进行处理。那么我该如何修改您的示例来处理这个问题呢?您能准确地指定格式吗?这样我就可以清楚地了解它了?它是一个带有逗号分隔值的文本文件。-'第1句、第2句等。必要时,使用熊猫阅读csv文件并循环句子。请参阅,我只需要在生产代码中重新定位“found=False”。
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