【问题标题】:How to fix thiss error when taking a sample of OSM (OpenStreetMap) data?获取 OSM (OpenStreetMap) 数据样本时如何解决此错误?
【发布时间】:2021-04-07 05:40:27
【问题描述】:

我正在尝试获取 OSM 文件的样本,但一直遇到以下错误

我在下面有这段代码,但我不断收到以下错误:

错误:

    File "<ipython-input-31-e45dfe148a3d>", line 31
    output.write({'</osm>'})
    ^
    SyntaxError: invalid syntax

代码:

    import xml.etree.ElementTree as ET  # Use cElementTree or lxml if too slow
    import os
    
    OSM_FILE = os.path.join("/Users/projects/sandiego.osm")  
    
    SAMPLE_FILE = "sample.osm"
    
    
    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 = 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 10th top level element
        for i, element in enumerate(get_element(OSM_FILE)):
            if i % 50 == 0:
                output.write(str(ET.tostring(element, encoding='UTF-8'))
    
        output.write('</osm>')

【问题讨论】:

    标签: python xml xml-parsing openstreetmap


    【解决方案1】:

    您在第 29 行缺少括号: output.write(str(ET.tostring(element, encoding='UTF-8')))

    【讨论】:

    • 非常感谢!我现在收到以下错误:使用 open(SAMPLE_FILE, 'rb') 作为输出:----> 4 output.write('\n ') UnsupportedOperation: 写
    • @coryrobbins 好像您正在打开文件进行阅读,请尝试 open(SAMPLE_FILE, 'w')。
    猜你喜欢
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多