【问题标题】:nested tags and attributes in BeautifulSOUP and OpenStreetMap XMLBeautifulSOUP 和 OpenStreetMap XML 中的嵌套标签和属性
【发布时间】:2020-07-28 18:49:21
【问题描述】:

请帮助为该任务编写有意义的代码: 我需要计算 XML OpenStreet Map 文件中的所有标签“way”,每个标签中“nd”标签的数量,并输入标签“way”的 id,其中包括最大数量的标签“nd”。如果有多个 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)) 

【问题讨论】:

    标签: python xml beautifulsoup nodes openstreetmap


    【解决方案1】:

    您可以使用max()内置方法找到<way>标签中<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
    

    【讨论】:

    • 对不起,你能解释一下为什么我们要声明 key=lambda tag: int(tag['id'])) 作为排序参数吗?
    • @AnnaGhildina key=lambda tag: int(tag['id'])) 是参数,用于sorted() 函数。这意味着,&lt;way&gt; 标签按id=.. 参数排序。
    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2020-12-04
    相关资源
    最近更新 更多