我有一个 XML,每个标签的属性如下:
<?xml version= "1.0" encoding="ISO-8859-1" ?>
<month xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="my.xsd">
<day Day="2016-1-01">
<hour Hour="00:00">
<Variables>
<a>211.3</a>
<b>78.94</b>
<c>0.6</c>
</Variables>
</hour>
<hour Hour="12:00">
<Variables>
<a>155.5</a>
<b>85.5</b>
<c>0.42</c>
</Variables>
</hour>
</day>
</month>
我希望解析 XML 并转换为字典,但不使用标签,而是使用属性值。
我的意思是,如何能够制作类似于:
>>> print d['2016-1-01']['12:00']['b']
>>> 85.5
真正的 XML 有更多的天数和时间。这可能吗?
我能做的唯一解析它的方法是这个,但是如果你想在不同时间寻找几个不同的变量就很难了:
# Day
for child_day in root:
print child_day.tag, child_day.attrib
# Hour
for child_hour in child_day:
print '\t', child_hour.tag, child_hour.attrib
# Variables
for child_Variables in child_hour:
print '\t\t', child_Variables.find('b').text
有没有类似于this answer的函数这使得属性大小写与这个而不是标签相同?
请您参考如下方法:
您链接的答案是使用所谓的 dict comprehension .这是一个非常简单而优雅的解决方案,因为它将在 ElementTree 的每个级别执行相同的操作。生成该级别的 dict , 这样该函数就可以递归地调用自身。
但如果我理解正确的话,您将获取每个标签的不同属性,具体取决于您在 ElementTree 结构中所处的级别。用作 dict键,然后您将在底层将其切换为使用标签名称作为键,将文本作为值。所以我无法想出一个与您链接的答案中的解决方案一样优雅的解决方案。
我们也可以使用字典理解,但我们将不得不使用它几次(至少对于我想出的解决方案而言)。
听起来您希望获得 dict看起来像这样(给定您的示例 XML):
{
"2016-1-01": {
"12:00": {
"a": "155.5",
"b": "85.5",
"c": "0.42",
},
"00:00": {
"a": "211.3",
"b": "78.94",
"c": "0.6",
},
},
}
为此,您需要 3 个函数; 1 处理 dict 每一层的创建(天、小时和变量)。它们的外观如下:
def month_etree_to_dict(month):
d_list = month.getchildren()
d_dict = {d.attrib["Day"]: day_etree_to_dict(d) for d in d_list}
return d_dict
def day_etree_to_dict(day):
h_list = day.getchildren()
h_dict = {h.attrib["Hour"]: hour_etree_to_dict(h) for h in h_list}
return h_dict
def hour_etree_to_dict(hour):
v_list = hour.getchildren()[0].getchildren()
v_dict = {v.tag: v.text for v in v_list}
return v_dict
函数month_etree_to_dict生成 dict其中键是每一天的日期。这些值是使用 day_etree_to_dict 生成的字典功能。 day_etree_to_dict函数通过调用 hour_etree_to_dict 每小时执行相同的操作功能。 hour_etree_to_dict通过在 ElementTree 中向下跳一个额外的级别,函数的工作方式略有不同。所以它可以遍历 <Variables> Element的 child ( <a> 、 <b> 和 <c> )使用他们的标签名称作为 dict 的键及其值的文本。
我希望这对您有意义并且对您有用。
