我需要从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中。
发布于 2019-08-13 13:15:24
您可以使用缓和的贪婪令牌,请参阅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'}https://stackoverflow.com/questions/57470304
复制相似问题