2014-02-18 26 views
1

我有一個kml文件,它有超過100萬字符的單元格。我想將小數從12減少到3.我導入了lxml和pykml。如何使用pykml減少本地kml文件中的座標十進制?

import pykml 
from pykml.helpers import set_max_decimal_places 
file1=open('\United States divisions. Level 2.kml') 
from os import path 
#set_max_decimal_places(file1, max_decimals={'longitude':3,'latitude':3,}) 

,我得到這個錯誤:

 39   index_no = 0 # longitude is in the first position 
    40   # modify <longitude> 
---> 41   for el in doc.findall(".//{http://www.opengis.net/kml/2.2}longitude"): 
    42    new_val = round(float(el.text), max_decimals[data_type]) 
    43    el.getparent().longitude = K.longitude(new_val) 

AttributeError的:「文件」對象有沒有屬性「的findall」

回答

0

這是因爲你正在加載的KML只是一個文件,它需要先解析。來源:http://pythonhosted.org/pykml/tutorial.html

In [29]: from pykml import parser 

... 

In [40]: kml_file = path.join(\ 
    ....:  '../src/pykml/test', \ 
    ....:  'testfiles/google_kml_developers_guide', \ 
    ....:  'complete_tour_example.kml') 

In [44]: with open(kml_file) as f: 
    ....:  doc = parser.parse(f) 

然後,您可以撥打:

....:  set_max_decimal_places(doc, max_decimals={'longitude':3,'latitude':3,}) 

更新:

使用你的代碼上面,我認爲這應該工作太:(from here

file1=open('\United States divisions. Level 2.kml') 
doc = fromstring(file1.read(), schema=Schema("ogckml22.xsd")) 
set_max_decimal_places(doc, max_decimals=3) 

更新:2

只需拔在您從您的評論中使用的最終代碼:

from lxml import etree 
from pykml.helpers import set_max_decimal_places 
from pykml import parser 

with open('\United States divisions. Level 2.kml') as f: 
    doc=parser.parse(f) 
    set_max_decimal_places(doc, max_decimals={'longitude':3,'latitude':3,}) 

print etree.tostring(doc, pretty_print=True) 
outfile = file(file.rstrip('.py')+'.kml','w') 
outfile.write(etree.tostring(doc, pretty_print=True)) 
+0

所以 - 在第一種情況下,我希望你只需將文件寫回磁盤?在第二期中,我希望你有一個不合法的KML屬性集 - 嘗試驗證你的文檔。如果是這種情況,只需使用第一種方法,因爲您不需要*有一個有效的KML來進行這些更新或使用它。 – Matthew

+0

我的意見之前,你最後一個在你刪除/重新添加它之前處理此評論。 – Matthew

+0

我建議你從鏈接文檔中的示例開始,只使用您在腳本中設置的字符串。一旦工作正常,請嘗試加載文件的摘錄(在巨大文檔中​​的新測試文件中記錄幾條記錄),並確保按預期工作。然後繼續處理整個事情。 – Matthew