使用 Python 和 BeautifulSoup 从 XML 文件创建字典

Creating a Dictionary from an XML file using Python and BeautifulSoup

请原谅我的初学者Python。我需要使用 BeautifulSoup 遍历 XML 文件中的某个元素。

我正在尝试从天气网站创建的 XML 文件中获取信息,现在我正在像这样保存 XML;

def aber_forcast():
    url = "http://api.met.no/weatherapi/locationforecast/1.9/?lat=52.41616;lon=-4.064598"
    response = requests.get(url)
    xml_text=response.text
    soup= bs4.BeautifulSoup(xml_text, "xml") 
    f = open('file.xml', "w")
    f.write(soup.prettify())
    f.close()
    return (soup)

我正在尝试计算元素 'symbol id' 的出现次数。我将需要创建符号 ID 及其在整个 XML 中出现次数的图表。我可以使用以下方法将所有 symbol_id 放入一个列表中;

with open ('file.xml') as file:
    soup = bs4.BeautifulSoup(file, "xml")
    symbol_id = soup.find_all("symbol")   
    print(symbol_id)

有 'Cloud'、'Rain' 等以及与之相关的 ID 号,查看了 Whosebug,我假设它类似于下面的代码,我需要创建一个相关数字和 ID 的字典然后计算迭代次数。

def parseLog(file):
    file = sys.argv[1]
    handler = open(file).read()
    soup = Soup(handler)
    for sym in soup.findAll('symbol'):
        msg_attrs = dict(sym.attrs)
        f_user = sym.find('symbol id').user
        f_user_dict = dict(f_user.attrs)
        print ((f_user_dict[u'symbols'], sym.find('number').decodeContents()) 

如果问题没有多大意义,我将不胜感激任何帮助或建议。我对这一切还是陌生的。

您可以使用 xmltodict https://github.com/martinblech/xmltodict

xmltodict.parse("""
<?xml version="1.0" ?>
<person>
<name>john</name>
<age>20</age>
</person>""")
# {u'person': {u'age': u'20', u'name': u'john'}}`

不完全确定您在寻找什么,但通过列表简单迭代计算 ID 的出现次数将如下所示。

#get data
url = "http://api.met.no/weatherapi/locationforecast/1.9/?lat=52.41616;lon=-4.064598"
response = requests.get(url)
xml_text=response.text
soup= bs4.BeautifulSoup(xml_text, "xml") 
symbol_id = soup.find_all("symbol")

# create dictionary
d = {}
for item in symbol_id:
    d[item['id']] = d.get(item['id'], 0) + 1

print(d)

{'Cloud': 15,
 'Drizzle': 9,
 'DrizzleSun': 6,
 'LightCloud': 2,
 'LightRainSun': 2,
 'PartlyCloud': 13,
 'Rain': 1,
 'Sun': 18}

您也可以在一行中使用 Counter

from collections import Counter
Counter([x['id'] for x in soup.find_all("symbol")])