Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式:如何匹配2个模式并将其保存到字典?_Python_Regex_Python 3.x_List_Dictionary - Fatal编程技术网

Python 正则表达式:如何匹配2个模式并将其保存到字典?

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

我需要从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 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你应该看看这是什么意思?@IzzuddinJamaluddin
re.DOTALL
re.DOTALL
意味着
字符也将匹配换行符。没有它,除了新线之外,它什么都匹配。
{'Sophia': 'Cat', 'Julia': 'Bird', 'Max': 'Dog'}