首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >RegEx :如何匹配2个模式并将其保存到字典?

RegEx :如何匹配2个模式并将其保存到字典?
EN

Stack Overflow用户
提问于 2019-08-13 10:14:18
回答 1查看 96关注 0票数 2

我需要从log.txt创建一个这样的字典列表(匹配主人和他们的宠物类型

代码语言:javascript
复制
dictionary = {
  "Sophia": "Cat",
  "Julia": "Bird",
  "Max": "Dog"
}

log.txt

代码语言:javascript
复制
Pet Owner : Sophia
    Colour : Blue
    Pet Type : Cat
    From : India
    Price : High

Pet Owner : Bruce
    Not own pet

Pet Owner : Sean
    Not own pet

Pet Owner : Julia
    Colour : Yellow
    Pet Type : Bird
    From : Israel
    Price : Low

Pet Owner : Bean
    Not own pet

Pet Owner : Max
    Colour : Green
    Pet Type : Dog
    From : Italy
    Price : Normal

Pet Owner : Clarie
    Not own pet

到目前为止,我所尝试的

代码语言:javascript
复制
import re

log = open("log.txt", "r")
txt = log.read()
log.close()

x = re.search("^Pet.Owner.+", txt)
print(x.group())

我停留在这里,我不知道如何让regEx返回我想要的2关键字,并将其保存到dictionary.txt中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-13 13:15:24

您可以使用缓和的贪婪令牌,请参阅regex101

代码语言:javascript
复制
s = '''Pet Owner : Sophia
    Colour : Blue
    Pet Type : Cat
    From : India
    Price : High

Pet Owner : Bruce
    Not own pet

Pet Owner : Sean
    Not own pet

Pet Owner : Julia
    Colour : Yellow
    Pet Type : Bird
    From : Israel
    Price : Low

Pet Owner : Bean
    Not own pet

Pet Owner : Max
    Colour : Green
    Pet Type : Dog
    From : Italy
    Price : Normal

Pet Owner : Clarie
    Not own pet'''

import re

out = dict( re.findall(r'Pet Owner : (\w+)(?:(?!Pet Owner :).)*Pet Type : (\w+)', s, flags=re.DOTALL) )

print(out)

打印:

代码语言:javascript
复制
{'Sophia': 'Cat', 'Julia': 'Bird', 'Max': 'Dog'}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57470304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档