本文介绍了如何在Python中从OSM文件提取和可视化数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在桌面上下载了OpenStreetMap文件,并在jupyter笔记本中使用了OSM文件.

I have downloaded an OpenStreetMap file on my desktop , and I have used my OSM file in the jupyter notebook.

我的代码:

import xml.etree.cElementTree as ET
osm_file = "ahmedabad_india.osm"

for event, elem in ET.iterparse(osm_file, events=("start",)):
     print(elem)
     # prints the Element 'osm' at 0x03A7DC08>
     #<Element 'bounds' at 0x03A7DDA0>
     #<Element 'node' at 0x03A7DE90>
     #<Element 'tag' at 0x03A7DF08> and so on ...

我想查看所有tags的内容,即 <'node', 'id', 'name', ...>等.

I'd like to see the contents of all the tags i.e. <'node', 'id', 'name', ...> and so on.

我尝试使用elem标记,但是没有打印任何内容.

I tried using elem tag but, it prints nothing.

任何人都可以帮助我弄清楚,谁可以获取节点,方式等标记的内容.

Can anyone help me to figure out, who to get the contents of tags like node, ways etc.

推荐答案

您可以通过 .osm文件中提取所有数据. ="noreferrer"> PyOsmium (一种用于处理OpenStreetMap数据的快速灵活的C ++库),然后使用 熊猫 :

You can extract all the data from an .osm file through PyOsmium (A fast and flexible C++ library for working with OpenStreetMap data) and then handle it with Pandas:

代码:

import osmium as osm
import pandas as pd

class OSMHandler(osm.SimpleHandler):
    def __init__(self):
        osm.SimpleHandler.__init__(self)
        self.osm_data = []

    def tag_inventory(self, elem, elem_type):
        for tag in elem.tags:
            self.osm_data.append([elem_type, 
                                   elem.id, 
                                   elem.version,
                                   elem.visible,
                                   pd.Timestamp(elem.timestamp),
                                   elem.uid,
                                   elem.user,
                                   elem.changeset,
                                   len(elem.tags),
                                   tag.k, 
                                   tag.v])

    def node(self, n):
        self.tag_inventory(n, "node")

    def way(self, w):
        self.tag_inventory(w, "way")

    def relation(self, r):
        self.tag_inventory(r, "relation")


osmhandler = OSMHandler()
# scan the input file and fills the handler list accordingly
osmhandler.apply_file("muenchen.osm")

# transform the list into a pandas DataFrame
data_colnames = ['type', 'id', 'version', 'visible', 'ts', 'uid',
                 'user', 'chgset', 'ntags', 'tagkey', 'tagvalue']
df_osm = pd.DataFrame(osmhandler.osm_data, columns=data_colnames)
df_osm = tag_genome.sort_values(by=['type', 'id', 'ts'])

输出:

这篇关于如何在Python中从OSM文件提取和可视化数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 00:01