【问题标题】:sorting the tags and print id with coordinates使用坐标对标签和打印 ID 进行排序
【发布时间】:2020-08-07 14:16:33
【问题描述】:

我需要用地图整理数据openstreetmap文件。我只需要找到关闭的方式(第一个 nd 坐标等于最后一个),更重要的是,只有带有 key=='building' 的标签的方式。然后我需要打印出它的 id 并在下一个字符串上打印出带有元组列表的词汇表,其中包含节点的坐标,这些节点是以这种方式包含的。它可能看起来像这样:

28889642

[(55.5652795, 37.5695507), (55.5651145, 37.5702288), (55.5648475, 37.5700314), (55.5650147, 37.5693509), (55.5652795, 37.5695507)]



28911067

[(55.5683532, 37.5644676), (55.5682987, 37.5644271), (55.5679549, 37.5641683), (55.5679974, 37.5639919), (55.5683976, 37.5642929), (55.5686577, 37.5632112), (55.5687302, 37.5632692), (55.5687094, 37.5633574), (55.5687319, 37.5633741), (55.5686567, 37.5636906), (55.5686342, 37.5636738), (55.5685984, 37.5638247), (55.5686198, 37.5638406), (55.5684996, 37.5643462), (55.5684605, 37.5643171), (55.5684327, 37.5644347), (55.5683718, 37.5643896), (55.5683532, 37.5644676)]

我的代码允许我找到合适的方式并打印它们,但它没有看到带有适合这种方式的坐标的词汇表。

代码:

from urllib.request import urlopen, urlretrieve
from bs4 import BeautifulSoup
from urllib.request import  urlopen, urlretrieve

response = urlopen(' https://stepik.org/media/attachments/lesson/266078/mapcity.osm')
xml = response.read().decode('utf8')
soup = BeautifulSoup(xml, 'lxml')
dict = {}

for node in soup.find_all('node'):
    lat = node['lat']
    lon = node['lon']
    id = node['id']
    dict[id] = (lat, lon)

for way in soup.find_all('way'):
    if way.find_all('nd')[0]==way.find_all('nd')[-1]:
        for tag in way('tag'):
            if tag['k'] == 'building':
                print(way['id'])
            elif way['id'] in dict[id]:
                print(dict[id])

【问题讨论】:

  • 我改进了您帖子的格式,其他人也已经做了一些改进。请参阅Markdown Editing Help 了解如何为您的下一个问题正确格式化代码。 PS:我知道空格/新行的数量是个人喜好并且不会更改代码,但是每行代码之间的空行是非常罕见的,我认为大多数人会发现没有这么多的空行更容易阅读,因此我删除了许多空白行。希望你不要介意。

标签: python dictionary tags


【解决方案1】:

我不熟悉 BS。我再举一个例子。代码逻辑是相互关联的。希望对你有帮助。

from simplified_scrapy import SimplifiedDoc, utils, req
res = req.get('https://stepik.org/media/attachments/lesson/266078/mapcity.osm')
xml = res.read().decode('utf-8')
doc = SimplifiedDoc(xml)
dic = {}
for node in doc.nodes:
    lat = node['lat']
    lon = node['lon']
    id = node['id']
    dic[id] = (lat, lon)

for way in doc.selects('way'):
    nds = way.selects('nd>ref()') # Find all nd
    building = way.select('tag@k=building') # Judge whether there is a tag with k = building
    if nds[0]==nds[-1] and building:
        print(way['id'])
        print([dic[nd] for nd in nds if nd in dic])

结果:

28889642
[('55.5652795', '37.5695507'), ('55.5651145', '37.5702288'), ('55.5648475', '37.5700314'), ('55.5650147', '37.5693509'), ('55.5652795', '37.5695507')]
28911067
...

【讨论】:

  • 也许您知道如何导出不带括号的“lat”和“lon”值。我的意思是这样的:[(55.5652795, 37.5695507), (55.5651145, 37.5702288)??
  • 问题解决了,我已经用float函数来判断字典值了
猜你喜欢
  • 2016-07-26
  • 2023-03-30
  • 2021-08-19
  • 2023-03-20
  • 2021-08-30
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多