Skip to main content
 首页 » 编程设计

python之正则表达式 : How to match 2 pattern and save it to dictionary

2024年11月01日43JustinYoung

我需要从 log.txt 中创建一个这样的字典列表(将所有者与其宠物类型相匹配)

dictionary = { 
  "Sophia": "Cat", 
  "Julia": "Bird", 
  "Max": "Dog" 
} 

日志.txt

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 
 
log = open("log.txt", "r") 
txt = log.read() 
log.close() 
 
x = re.search("^Pet.Owner.+", txt) 
print(x.group()) 

我卡在这里,我不知道如何让正则表达式返回我想要的 2 个关键字并将其保存到 dictionary.txt。

请您参考如下方法:

你可以使用tempered greedy token,见regex101 :

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) 

打印:

{'Sophia': 'Cat', 'Julia': 'Bird', 'Max': 'Dog'}