【发布时间】: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