当我运行我的代码时,我得到以下输出:
<Placemark>
<description>Picture<![CDATA[<img src='./files/picOne.jpg' width='400' height='300'>]]></description>
<styleUrl>#Photo</styleUrl>
<coordinates>-1.57245646667, 53.8090789556</coordinates>
</Placemark>
<styleUrl>#Photo</styleUrl>
<coordinates>-1.56958587633, 53.8345916667</coordinates>
</Placemark>
<Placemark>
<description>Picture<![CDATA[<img src='./files/picTwo.jpg' width='400' height='300'>]]></description>
<styleUrl>#Photo</styleUrl>
<coordinates>-1.57245646667, 53.8090789556</coordinates>
</Placemark>
<styleUrl>#Photo</styleUrl>
<coordinates>-1.56958333333, 53.8111916667</coordinates>
</Placemark>
</Folder>
</Document>
</kml>
我想在txt文件中输出以下内容:
<Placemark>
<description>Picture<![CDATA[<img src='./files/picOne.jpg' width='400' height='300'>]]></description>
<styleUrl>#Photo</styleUrl>
<coordinates>-1.57245646667, 53.8090789556</coordinates>
</Placemark>
<Placemark>
<description>Picture<![CDATA[<img src='./files/picTwo.jpg' width='400' height='300'>]]></description>
<styleUrl>#Photo</styleUrl>
<coordinates>-1.57245646667, 53.8090789556</coordinates>
</Placemark>
我不知道为什么我的脚本在每次循环后生成这些额外的代码。
**<styleUrl>#Photo</styleUrl>
<coordinates>-1.57245646667, 53.8111916667</coordinates>
</Placemark>**
以下是代码:
oneLat = ['53.8290433456','53.8346016367']
oneLong = ['-1.57245646667', '1.56959975983']
picList = ['picOne.jpg', 'picTwo.jpg']
coordPairs = zip((-float(x) for x in oneLong), (float(x) for x in oneLat))
with open("temp.txt",'w') as f:
increment = 0
while increment < len(picList):
f.write("\n\n<Placemark>\n")
f.write("\t\t\t<description>Picture<![CDATA[<img src='./files/{}' width='400' height='300'>]]></description>\n".format(picList[increment]))
increment = increment + 1
for coord in coordPairs:
f.write("\t\t<styleUrl>#Photo</styleUrl>\n")
f.write("\t\t<coordinates>{}, {}</coordinates>\n".format(*coord))
f.write("</Placemark>\n\n")
f.write('''
</Folder>
</Document>
</kml>''')
如果有人可以提供帮助,我们将不胜感激
答案 0 :(得分:2)
您的代码完全符合指示。对于每个坐标对,输出该部分。如果您不想要它,请将其删除。实际上,我认为您只想更改生成结束标记的代码的缩进:
for coord in coordPairs:
f.write("\t\t<styleUrl>#Photo</styleUrl>\n")
f.write("\t\t<coordinates>{}, {}</coordinates>\n".format(*coord))
f.write("</Placemark>\n\n")
但是,我建议您使用正确的XML生成器,这样就可以避免这种错误。