如何使用pykml减少本地kml文件中的坐标十进制?

时间:2014-02-18 17:11:10

标签: python-2.7 decimal kml lxml findall

我有一个kml文件,其中包含超过100万字符的单元格。我想将十进制数从12减少到3.我导入了lxml和pykml。

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:'file'对象没有属性'findall'

1 个答案:

答案 0 :(得分: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))