【问题标题】:How to get groupdict from multi-line string using regex如何使用正则表达式从多行字符串中获取 groupdict
【发布时间】:2018-10-26 17:07:17
【问题描述】:

我尝试使用正则表达式从多行字符串中获取字典,但我遇到了正确分隔行的问题。

这是我尝试过的......

import re

text = '''\n\n\nName: Clash1\nDistance: -1.274m\nImage Location: navis_raport_txt_files\\cd000001.jpg\nHardStatus: New\nClash Point: 1585.236m, 193.413m'''
clash_data = re.compile('''
    (?P<clash_number>Clash\d+)\n
    (?P<clash_depth>\d.\d{3})\n
    (?P<image_location>cd\d+.jpg)\n
    (?P<clash_status>\w{2:})\n
    (?P<clash_point>.*)\n
    (?P<clash_grid>\w+-\d+)\n
    (?P<clash_date>.*)''', re.I | re.VERBOSE)
print(clash_data.search(text).groupdict())

这个类似的例子效果很好:

import re

MHP = ['''MHP-PW-K_SZ-117-R01-UZ-01 - drawing title 123''',
       'MHP-PW-K_SZ-127-R01WIP - drawing title 2',
       'MHP-PW-K_SZ-107-R03-UZ-1 - drawing title 3']

fields_from_name = re.compile('''
    (?P<object>\w{3})[-_]
    (?P<phase>\w{2})[-_]
    (?P<field>\w)[-_]
    (?P<type>\w{2})[-_]
    (?P<dr_number>\d{3})[-_]
    [-_]?
    (?P<revision>\w\d{2})?
    (?P<wip_status>WIP)?
    [-_]?
    (?P<suplement>UZ-\d+)?
    [\s-]+
    (?P<drawing_title>.*)
    ''', re.IGNORECASE | re.VERBOSE)
for name in MHP:
    print(fields_from_name.search(name).groupdict())

为什么我的尝试不像示例那样工作?

【问题讨论】:

  • 在字符串文字中添加r前缀,当使用re.X标志时,有\ns没有意义。即re.compile(''' -> re.compile(r'''
  • 谢谢,我之前试过这样做,但它不起作用。我收到错误:“NoneType”对象没有属性“groupdict”

标签: python regex dictionary


【解决方案1】:

它不起作用仅仅是因为Pattern.search() 没有找到匹配项。根据您正在模仿的工作示例,您还需要匹配输出字典中所需的命名捕获组之间的字符(以便整个模式返回匹配项)。

以下示例使用.*\n.* 作为一种蛮力方法,通过匹配最后一个捕获组之后的任何非换行符,然后匹配换行符,然后匹配任何非-下一个捕获组之前的换行符(您可能希望比这更精确,但它说明了问题)。我只包含了您的前 3 个组,因为我没有按照您在 &lt;clash_status&gt; 组中使用正则表达式的意图。

import re

text = '\n\n\nName: Clash1\nDistance: -1.274m\nImage Location: navis_raport_txt_files\\cd000001.jpg\nHardStatus: New\nClash Point: 1585.236m, 193.413m'

clash_data = re.compile(r'(?P<clash_number>Clash\d+).*\n.*'
                        r'(?P<clash_depth>\d.\d{3}).*\n.*'
                        r'(?P<image_location>cd\d+.jpg)', re.I | re.VERBOSE)

result = clash_data.search(text).groupdict()

print(result)
# OUTPUT
# {'clash_number': 'Clash1', 'clash_depth': '1.274', 'image_location': 'cd000001.jpg'}

【讨论】:

  • 感谢您的明确答复。我是初学者,这就是为什么我模仿我在互联网上找到的一些解决方案,现在我可以深入研究这个问题了。
猜你喜欢
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
相关资源
最近更新 更多