1

我有一个包含超过 100 万个字符的单元格的 kml 文件。我想将小数位数从 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:“文件”对象没有属性“findall”

4

1 回答 1

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,})

更新:

使用上面的代码,我认为这也应该有效:(从这里开始

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))
于 2014-02-18T17:16:05.910 回答