9

我正在使用 pyKML 模块从给定的 KML 文件中提取坐标。

我的Python代码如下:

from pykml import parser
fileobject = parser.fromstring(open('MapSource.kml', 'r').read())
root = parser.parse(fileobject).getroot()
print(xml.Document.Placemark.Point.coordinates)

但是,在运行此程序时,我收到以下错误:

ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

寻找解决方案,我遇到了这个解决方案http://twigstechtips.blogspot.in/2013/06/python-lxml-strings-with-encoding.html从我尝试过的地方(我不确定是正确的方法):

from pykml import parser
from lxml import etree
from os import path
kml_file = open('MapSource.kml', 'r')
parser = etree.XMLParser(recover=True)
xml = etree.fromstring(kml_file, parser)
print(xml.Document.Placemark.Point.coordinates)

这给了我ValueError: can only parse strings. 我解析 KML 并获取该结构的坐标的正确方法是什么?

4

1 回答 1

2

在上面的示例中,root = parser.parse(fileobject).getroot()在文件内容上调用 parse() 作为从前一行的 fromstring() 函数返回的字符串。

使用 pyKML 解析 KML 文件有两种方法:

1:使用parse.parse()解析文件。

from pykml import parser
with open('MapSource.kml', 'r') as f:
  root = parser.parse(f).getroot()
print(root.Document.Placemark.Point.coordinates)

2:使用parse.parsestring()解析字符串内容。

from pykml import parser
with open('MapSource.kml', 'rb') as f:
  s = f.read()
root = parser.fromstring(s)
print(root.Document.Placemark.Point.coordinates)

如果 KML 文件将 XML prolog 标头作为非 UTF8 编码的第一行并尝试使用“r”作为文本读取文件,而使用“rb”作为二进制格式读取文件,则方法 #2 可能会失败。

如果在 KML 文档中未正确指定编码,则注释解析可能会失败。由于名称和描述中包含国际字符和图形字符,因此在下面的示例中使用了 ISO-8859-1 编码。省略编码或使用“UTF-8”会使其成为无效的 XML 文件。

<?xml version="1.0" encoding="ISO-8859-1"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
  <Placemark>
    <name>Río Grande</name> 
    <description>
      Location: 18° 22′ 49″ N, 65° 49′ 53″ W
    </description>
    ...
</kml>
于 2020-08-27T17:08:54.180 回答