2014-03-18 32 views
-1

當我運行我的代碼,我得到以下的輸出:停止循環創建不需要的代碼?

<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

嗯是的 - 但我不希望它生成該代碼。我問我怎麼能做到我想要的:) – BubbleMonster

回答

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生成代替,這樣,這樣的錯誤是從根本上避免。

+0

感謝您的評論 - 我完全誤讀了問題的要求。 –

+0

謝謝康拉德。我認爲這將是縮進。將盡快選擇正確答案。 – BubbleMonster