比逐行读取更有效(Python中的KML)

时间:2013-10-09 08:38:48

标签: python performance kml data-manipulation

所以我试图编写一个程序(没有依赖项)来读取Google地图中的KML文件(见下文),只获取坐标并将它们存储在Matrix中,以便以后进行数据操作。

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
  <name>Driving directions to Commercial St/A1202</name>
  <description><![CDATA[]]></description>
  <Style id="style1">
    <IconStyle>
      <Icon>
        <href></href>
      </Icon>
    </IconStyle>
  </Style>
  <Style id="style2">
    <LineStyle>
      <color>73FF0000</color>
      <width>5</width>
    </LineStyle>
  </Style>
  <Style id="style3">
    <IconStyle>
      <Icon>
        <href></href>
      </Icon>
    </IconStyle>
  </Style>
  <Placemark>
    <name>From: Unknown road</name>
    <styleUrl>#style1</styleUrl>
    <Point>
      <coordinates>-0.168942,51.520180,0.000000</coordinates>
    </Point>
  </Placemark>
  <Placemark>
    <name>Driving directions to Commercial St/A1202</name>
    <styleUrl>#style2</styleUrl>
    <ExtendedData>
      <Data name="_SnapToRoads">
        <value>true</value>
      </Data>
    </ExtendedData>
    <LineString>
      <tessellate>1</tessellate>
      <coordinates>
        -0.168942,51.520180,0.000000
        -0.167752,51.520447,0.000000
        -0.167371,51.520481,0.000000
      </coordinates>
    </LineString>
  </Placemark>
  <Placemark>
    <name>To: Commercial St/A1202</name>
    <styleUrl>#style3</styleUrl>
    <Point>
      <coordinates>-0.073247,51.516960,0.000000</coordinates>
    </Point>
  </Placemark>
</Document>
</kml>

虽然这对于像上面那样的小文件来说效率不高,但我有500 + KB文件可以解析!那么关于有效方法的任何建议(不涉及&#34;非标准&#34;需要安装的进口)只是获取这些坐标并将它们存储为矩阵?

1 个答案:

答案 0 :(得分:1)

所以,以下应该是你。通过依赖关系我假设你的意思是在Python附带的标准库之外(我不确定你如何在没有标准库的情况下安装python)....

import xml.etree.ElementTree as ET

print 'Starting'

tree = ET.parse('sample_data.xml')
root = tree.getroot()

for child in root.findall('.//{http://earth.google.com/kml/2.2}coordinates'):
    print child.text

如果你真的不能使用ElementTree,那么你遇到的问题比XML处理的效率要大。

顺便说一句......两分钟(或更短)的谷歌搜索会让你得到这个答案。