如何从OSM文件中获取元素的系统样本

时间:2016-09-01 04:02:10

标签: python

  

我正在尝试从大型OSM文件中获取系统的元素样本,但我得到“需要一个类似字节的对象,而不是'str'”错误。这是我正在使用的代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import xml.etree.ElementTree as ET  # Use cElementTree or lxml if too slow

OSM_FILE = "chattanooga.osm"  # Replace this with your osm file
SAMPLE_FILE = "sample.osm"

k = 100  # Parameter: take every k-th top level element

def get_element(osm_file, tags=('node', 'way', 'relation')):
    """Yield element if it is the right type of tag
    Reference:
    http://stackoverflow.com/questions/3095434/inserting-newlines-in-xml-file-generated-via-xml-etree-elementtree-in-python
    """
    context = iter(ET.iterparse(osm_file, events=('start', 'end')))
    _, root = next(context)
    for event, elem in context:
        if event == 'end' and elem.tag in tags:
            yield elem
            root.clear()


with open(SAMPLE_FILE, 'wb') as output:
    output.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    output.write('<osm>\n  ')

    # Write every kth top level element
    for i, element in enumerate(get_element(OSM_FILE)):
        if i % k == 0:
            output.write(ET.tostring(element, encoding='utf-8'))

    output.write('</osm>')
  

这是我得到的错误

谢谢大家

TypeError                                 Traceback (most recent call last)
<ipython-input-26-349a323b1196> in <module>()
     23 
     24 with open(SAMPLE_FILE, 'wb') as output:
---> 25     output.write('<?xml version="1.0" encoding="UTF-8"?>\n')
     26     output.write('<osm>\n  ')
     27 

TypeError: a bytes-like object is required, not 'str'

0 个答案:

没有答案