【问题标题】:RegEx : How to match 2 pattern and save it to dictionary?正则表达式:如何匹配 2 个模式并将其保存到字典中?
【发布时间】: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


【解决方案1】:

你可以使用回火贪婪令牌,见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'}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 2014-08-22
  • 2016-07-04
  • 2018-07-07
  • 1970-01-01
相关资源
最近更新 更多