我使用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并在该结构中获取坐标的正确方法是什么?
发布于 2020-08-27 17:08:54
在上面的示例中,root = parser.parse(fileobject).getroot()调用文件内容的解析()作为从上一行的from ()函数返回的字符串。
有两种方法可以使用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)方法2可能会失败,如果KML文件有一个XML头作为非UTF8 8编码的第一行,并尝试以'r‘作为文本与'rb’读取二进制格式的文件。
注如果在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>https://stackoverflow.com/questions/26074069
复制相似问题