【发布时间】:2019-12-19 13:42:38
【问题描述】:
我需要从 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())
我卡在这里,我不知道如何让正则表达式返回我想要的 2 关键字并将其保存到 dictionary.txt。
【问题讨论】:
-
您可以使用此
(?:Pet Owner|Pet Type) : ([^\n]+)模式,然后从获得的结果中一次使用两个块构建对象 -
@CodeManiac 喜欢这样吗?
x = re.search("(?:Pet Owner|Pet Type) : ([^\n]+)", txt)?它给出了输出Pet Owner : Sophia这是什么意思? -
@IzzuddinJamaluddin 你应该看看这个stackoverflow.com/questions/52603287/…
标签: python regex python-3.x list dictionary