代码:正则表达式处理xml文件.py
# xml文件内容如下:
"""
VOC2007
000005.jpg
The VOC2007 Database
PASCAL VOC2007
flickr
325991873
archintent louisville
?
500
375
3
0
chair
Rear
0
0
263
211
324
339
chair
Unspecified
0
0
165
264
253
372
chair
Unspecified
1
1
5
244
67
374
chair
Unspecified
0
0
241
194
295
299
chair
Unspecified
1
1
277
186
312
220
"""
import re
# xmlPath = r'000020.xml' # 内容相对少
xmlPath = r'000005.xml' # 内容相对多
xmlFile = open(xmlPath)
xml = xmlFile.read()
# print(xml)
# print(type(xml)) #
s = r"""
(.*?).*?""" + \
r"""(.*?).*?""" + \
r"""(.*?).*?""" + \
r"""(.*?).*?""" + \
r"""(.*?).*?""" + \
r"""(.*?).*?""" + \
r""".*?"""
pattern = re.compile(s,re.S)
items = re.findall(pattern, xml)
for item in items:
difficult = item[1]
classType = item[0]
xmin = int(item[2])
ymin = int(item[3])
xmax = int(item[4])
ymax = int(item[5])
info = \
"difficult:{0:^4}classType:{1:^10}xmin:{2:^6}ymin:{3:^6}xmax:{4:^6}ymax:{5:^6}".format(
difficult,classType,xmin,ymin,xmax,ymax)
print(info)
xmlFile.close()
控制台输出信息:
Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。
尝试新的跨平台 PowerShell https://aka.ms/pscore6
PS C:\Users\chenxuqi\Desktop\新建文件夹\test> & 'D:\Python\Python37\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2020.11.358366026\pythonFiles\lib\python\debugpy\launcher' '53259' '--' 'c:\Users\chenxuqi\Desktop\新建文件夹\test\正则表达式处理xml文件.py'
difficult: 0 classType: chair xmin: 263 ymin: 211 xmax: 324 ymax: 339
difficult: 0 classType: chair xmin: 165 ymin: 264 xmax: 253 ymax: 372
difficult: 1 classType: chair xmin: 5 ymin: 244 xmax: 67 ymax: 374
difficult: 0 classType: chair xmin: 241 ymin: 194 xmax: 295 ymax: 299
difficult: 1 classType: chair xmin: 277 ymin: 186 xmax: 312 ymax: 220
PS C:\Users\chenxuqi\Desktop\新建文件夹\test>
本文分享 CSDN - 敲代码的小风。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。