【问题标题】:regex search nested dictionary and stop on first match (python)正则表达式搜索嵌套字典并在第一次匹配时停止(python)
【发布时间】: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


    【解决方案1】:
    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
    

    【讨论】:

    • 我的生产代码从文件中读取行进行处理。那么我该如何修改你的示例来处理这个问题呢?
    • 您能否具体说明格式是什么,以便我能有一个清晰的概念?
    • 这是一个以逗号分隔的文本文件。 - 'sentence 1', 'sentence 2', etc.
    • 使用 pandas 读取 csv 文件并在必要时循环句子。参考stackoverflow.com/questions/14365542/…
    • 我只需要在我的生产代码中重新定位“found = False”。
    猜你喜欢
    • 2022-12-03
    相关资源
    最近更新 更多