0

如何从下面的文本中提取 WESTBOUNDINGCOORDINATE、NORTHBOUNDINGCOORDINATE、EASTBOUNDINGCOORDINATE 和 SOUTHBOUNDINGCOORDINATE?但是,所有元文件都没有在同一行中的文本,例如,罚款一个
在第 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 值并不总是在同一行。

4

1 回答 1

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
}

然后,您可以从字典中获取所需的任何坐标。

于 2013-08-29T05:23:18.243 回答