我正在使用 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 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 并获取该结构的坐标的正确方法是什么?
在上面的例子中,root = parser.parse(fileobject).getroot()
正在对文件内容调用 parse() 作为从上一行的 fromstring() 函数返回的字符串。
使用 pyKML 解析 KML 文件有两种方法:
1:使用解析.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)