如何从下面的文字中提取WESTBOUNDINGCOORDINATE,NORTHBOUNDINGCOORDINATE,EASTBOUNDINGCOORDINATE和SOUTHBOUNDINGATE? 但是,所有元文件都没有同一行中的文本,例如,精细文件有 第2行的WESTBOUNDINGCOORDINATE但第2行有第4行。请帮助......
GROUP = BOUNDINGRECTANGLE
OBJECT = WESTBOUNDINGCOORDINATE
NUM_VAL = 1
VALUE = 80.8290376770946
END_OBJECT = WESTBOUNDINGCOORDINATE
OBJECT = NORTHBOUNDINGCOORDINATE
NUM_VAL = 1
VALUE = 39.9999999964079
END_OBJECT = NORTHBOUNDINGCOORDINATE
OBJECT = EASTBOUNDINGCOORDINATE
NUM_VAL = 1
VALUE = 104.443461525786
END_OBJECT = EASTBOUNDINGCOORDINATE
OBJECT = SOUTHBOUNDINGCOORDINATE
NUM_VAL = 1
VALUE = 29.9999999973059
END_OBJECT = SOUTHBOUNDINGCOORDINATE
END_GROUP = BOUNDINGRECTANGLE
我的代码:
metafiles = glob.glob("D://*.txt")
for f in metafiles:
with open (f, 'r') as infile:
lines = infile.readlines()
WESTBOUNDINGCOORDINATE = lines[4][29:45]
print (WESTBOUNDINGCOORDINATE)
问题是WESTBOUNDINGCOORDINATE值并不总是在同一行。
答案 0 :(得分:0)
尝试遍历文件,忽略所有空行,并查找以字符串"OBJECT"
开头并以您想要的坐标结束的行。
例如:
def parse(filepath):
with open(filepath) as f:
contents = f.readlines()
output = {}
group = {}
inside_group = False
for line in contents:
line = line.strip()
if line == '':
continue
type, value = line.split('=')
type = type.strip()
value = value.strip()
if type == 'OBJECT':
inside_group = True
elif type == 'END_OBJECT':
output[value] = group
inside_group = False
group = {}
elif inside_group:
group[type] = value
return output
这应该返回以下形式的字典:
>>> parse('file1.txt')
{
"WESTBOUNDINGCOORDINATE": {
"NUM_VAL": 1,
"VALUE": 80.829037677094
},
"NORTHBOUNDINGCOORDINATE": {
"NUM_VAL": 1,
"VALUE": 39.9999999964079
},
# etc
}
然后,您可以从字典中获取所需的任何坐标。