我仍然是python的新手,我正在尝试将列表(List2)上的位置导出到kml文件中,然后在谷歌地图上显示结果。我真的不知道我在做什么,所有我得到的是每个“,符号周围的语法错误。有人可以帮助我。
KMLFile = open("KML.txt", "w")
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
f.write(" <Placemark>")
f.write(" <decription>" + str(row[0]) + "</description>")
f.write(" <Point>")
f.write(" <coordinates>" + str(row[2]) + str(row[1])"</coordinates>")
f.write(" </Point>")
f.write(" </Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
KMLFile = close()
答案 0 :(得分:4)
您应该使用python KML包,例如simplekml或pyKML,而不是在打印语句中对XML输出进行硬编码。 simplekml API不仅简化了编写KML,还生成了有效的KML,代码更清晰,更易于理解。
import simplekml
kml = simplekml.Kml()
for row in List2:
kml.newpoint(description=row[0],
coords=[(row[2], row[1])]) # lon, lat, optional height
kml.save("test.kml")
将此测试输入用于单点:
List2 = [ [ 'description', 51.500152, -0.126236 ] ] # description, lat, lon
KML输出将是:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
<Document id="feat_1">
<Placemark id="feat_2">
<description>description</description>
<Point id="geom_0">
<coordinates>-0.126236,51.500152,0.0</coordinates>
</Point>
</Placemark>
</Document>
</kml>
答案 1 :(得分:2)
在您的代码中,您还没有定义应该引用您要写入的文件对象的变量f
。你可以做
f = open("KML.txt", "w")
f.write("<KML_File>\n")
...
f.close()
或更好:
with open("KML.txt", "w") as f:
f.write("<KML_File>\n")
...
,即使中间的某些代码失败,也要确保始终关闭文件。
对于编写XML文件,您可能需要查看Python xml-package。
答案 2 :(得分:1)
简而言之:
KMLFile
更改为f
,反之亦然。close()
方法:f.close()
。您的更正代码:
f = open("KML.txt", "w")
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
f.write("\t<Placemark>")
f.write("\t\t<decription>" + str(row[0]) + "</description>")
f.write("\t\t<Point>")
f.write("\t\t\t<coordinates>" + str(row[2]) + str(row[1]) + "</coordinates>")
f.write("\t\t</Point>")
f.write("\t</Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
f.close()
此外,如果您不想编写f.close()
行并让python管理文件关闭:
with open("KML.txt", "w") as f:
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
f.write("\t<Placemark>")
f.write("\t\t<decription>" + str(row[0]) + "</description>")
f.write("\t\t<Point>")
f.write("\t\t\t<coordinates>" + str(row[2]) + str(row[1]) + "</coordinates>")
f.write("\t\t</Point>")
f.write("\t</Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
最后,如果您不想在+
行中添加多个f.write()
,则还可以选择format()
方法:
f.write("\t\t\t<coordinates>{}{}/coordinates>".format(row[2], row[1]))
答案 3 :(得分:0)
import geopandas as gpd
polys = gpd.GeoDataFrame(df)
polys.to_file(r'../docs/database.kml', driver = 'KML')