regex - 正则表达式搜索嵌套字典并在第一次匹配时停止(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))
解决方案
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
推荐阅读
- javascript - 如何使用 JS 在后台使用 Google Chrome 扩展访问不同的 URL?
- gatsby - GatsbyJS StaticQuery 是在构建时还是在运行时获取数据?
- python - 尝试根据三个常见列匹配两个 df,但它们都不相同
- excel - 将内容从一个工作簿复制到另一个工作簿,以特殊方式粘贴
- r - Replacing spread() with pivot_wider()
- codenameone - Codename One WebSocket + Spring Boot
- windows - Sanitize batch inputs against quotation marks?
- javascript - 如何添加方法
- android - Localytics Firebase 推送通知不适用于适用于 Android 的 Xamarin Forms
- go - 如何从 Cloud Identity Aware 代理获取用户电子邮件