Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python和BeautifulSoup从XML文件创建字典_Python_Xml_Iterate - Fatal编程技术网

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

使用Python和BeautifulSoup从XML文件创建字典,python,xml,iterate,Python,Xml,Iterate,请原谅我的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=respon

请原谅我的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中出现的次数。我可以通过使用将所有符号id放入一个列表中

with open ('file.xml') as file:
    soup = bs4.BeautifulSoup(file, "xml")
    symbol_id = soup.find_all("symbol")   
    print(symbol_id)
有‘Cloud’、‘Rain’等,还有一个与之相关的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()) 

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

您可以使用
xmltodict

xmltodict.parse(“”)
厕所
20
""")
#{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}
您也可以使用
计数器在一行中执行此操作

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

这正是我想要的,只要一行代码,当你知道怎么做的时候,它看起来很简单。非常感谢。:)没问题。请看我添加的一行答案。
from collections import Counter
Counter([x['id'] for x in soup.find_all("symbol")])