BeautifulSOUP和OpenStreetMap XML中的嵌套标记和属性

2024-05-03 23:48:55 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮助为任务编写有意义的代码: 我需要计算XML OpenStreet地图文件中所有标记“way”,每个标记中“nd”标记的数量,并输入标记“way”的id,其中包括最大数量的标记“nd”。如果有多个ide,则按字母顺序输入第一个ide。看起来很容易,但我不懂如何操作。(我只认为使用词汇是有用的) 代码如下:

from urllib.request import urlopen, urlretrieve

from bs4 import BeautifulSoup


resp = urlopen('https://stepik.org/media/attachments/lesson/245681/map2.osm') # 

xml = resp.read().decode('utf8') # 

soup = BeautifulSoup(xml, 'xml') # делаем суп с помощью lxml

cnt = 0

names ={}

for way in soup.find_all('way'): # go through the nodes

    flag=False

    for nd in way('nd'):

        flag=True

        if nd['k'] == 'id':

            name=nd['v']

    if flag:

        if name not in names:

            names[name]=0

        names[name]+=1

print(sort(names)) 

Tags: 代码nameinfrom标记importid数量
1条回答
网友
1楼 · 发布于 2024-05-03 23:48:55

您可以使用max()内置方法查找数量最大的<nd>标签

例如:

import requests
from bs4 import BeautifulSoup


url = 'https://stepik.org/media/attachments/lesson/245681/map2.osm'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

num_way = len(soup.select('way'))
w = max(sorted(soup.select('way:has(nd)'), reverse=True, key=lambda tag: int(tag['id'])), key=lambda tag: len(tag.select('nd')))

print('number of <way>:', num_way)
print('id:', w['id'])
print('quantity of <nd>:', len(w.select('nd')))

印刷品:

number of <way>: 3181
id: 227140108
quantity of <nd>: 249

相关问题 更多 >