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

标签 python xml loops

请原谅我对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)

我正在尝试计算元素“符号 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)

有“云”、“雨”等以及与之相关的 ID 号,浏览了 stackoverflow,我假设它类似于下面的代码,我需要创建一个关联号的字典,并且然后 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()) 

如果问题没有多大意义,任何帮助或建议都会非常抱歉,我对这一切还是新手。

最佳答案

不完全确定您要查找的内容,但通过列表进行简单迭代计算 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")])

关于python - 使用 Python 和 BeautifulSoup 从 XML 文件创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41365632/

相关文章:

c - 程序返回字符而不是字符串

python - Selenium WD Python 消息 : Invalid timeout type specified: sessionId

python - Pandas:简单的生长分析(比较)和 Fillna

xml - 比较忽略子元素顺序的 XML

mysql - Perl 和 MySQL 插入 XML 字符串导致错误 2006 "server gone away"

android - 聚焦时设置编辑文本边框

javascript - 上传多个文件并显示进度条

python - 将 JSON 转换为 pd.DataFrame

sql - PostGIS 2.3 按点分割线

java - (Java) 使用嵌套循环