Python 正则表达式:如何匹配2个模式并将其保存到字典?
我需要从log.txt中创建一个这样的字典列表(将所有者与他们的宠物类型匹配)Python 正则表达式:如何匹配2个模式并将其保存到字典?,python,regex,python-3.x,list,dictionary,Python,Regex,Python 3.x,List,Dictionary,我需要从log.txt中创建一个这样的字典列表(将所有者与他们的宠物类型匹配) dictionary = { "Sophia": "Cat", "Julia": "Bird", "Max": "Dog" } log.txt Pet Owner : Sophia Colour : Blue Pet Type : Cat From : India Price : High Pet Owner : Bruce Not own pet Pet O
dictionary = {
"Sophia": "Cat",
"Julia": "Bird",
"Max": "Dog"
}
log.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())
我被困在这里,我不知道如何使regEx返回我想要的2个关键字并将其保存到dictionary.txt。您可以使用令牌,请参阅: 印刷品:
{'Sophia': 'Cat', 'Julia': 'Bird', 'Max': 'Dog'}
您可以使用此
(?:宠物所有者|宠物类型):([^\n]+)
模式,然后从中每次使用两个块构建对象result@CodeManiac像这样x=re.search((?:宠物主人|宠物类型):([^\n]+)”,txt)
?它给出了输出:Sophia这是什么意思?@IzzuddinJamaluddin你应该看看这是什么意思?@IzzuddinJamaluddinre.DOTALLre.DOTALL意味着
字符也将匹配换行符。没有它,除了新线之外,它什么都匹配。
{'Sophia': 'Cat', 'Julia': 'Bird', 'Max': 'Dog'}