【问题标题】:cannot figure out how to populate a dictionary from an xml file无法弄清楚如何从 xml 文件中填充字典
【发布时间】:2019-12-04 21:48:56
【问题描述】:

我是 python 的新手。我在 2.7 中工作,我正在尝试解析 XML 文件以填充字典并跟踪变量名的使用次数(名称会改变,因此字典),它还需要跳过数字和变量名中的冒号。我知道我需要将它作为一个元素拉出来,以便我可以操纵它,但我不确定如何操作。请帮忙。这是我与一段 XML 代码一起回溯到的内容。

import xml.etree.ElementTree as ET

tree = ET.parse(sample.xml)
root = tree.getroot()

d = {}

for iec-source in root:

    variable_code = variable.find('variable-name')

if variable_code.text == #varibale is in dictionary add count

else #add to dictionary and add count

xml picture

【问题讨论】:

  • 你能解释一下字典中的键/值是什么吗?
  • .find.findall 方法使用 XPATH 字符串。 etree 文档有一个关于构建 XPATH 字符串的好部分,但基本上我怀疑你需要for variable_name in root.findall(".//variable-name")
  • 它们将是 xml 文件中的变量名。因此示例 5:Inspection,Inspection 将被添加到字典中并计数 1 次。我认为这将是计算使用了什么变量名以及它出现了多少次的最简单方法

标签: python xml


【解决方案1】:

首先,您需要提取所有 variable_name 节点。 .find 方法将返回与指定 XPATH 匹配的 first 节点。 .findall 方法将返回匹配的 all 节点数组。接下来,您将要处理文本。如果您知道 所有 变量名称都有冒号,则可以在字符串上使用.split()。最后,您可以使用if key in dict.keys() 来检查密钥是否存在。

import xml.etree.ElementTree as ET

tree = ET.parse("sample.xml")
root = tree.getroot()

dict = {}

# Loop through all nodes with tag <variable_name>
for variable_name in root.findall(".//variable_name"):

    text = variable_name.text    # Get the raw text from the xml

    variable = text.split(":")[1]    # Splits the text into an array
                                     # ["#","VARIABLE"]
                                     # keep the second element

    if variable in dict.keys():
        dict[variable] += 1    # Increment the count for that variable
    else:
        dict[variable] = 1     # Add the new variable to dict, initialize to 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-10
    • 2018-08-15
    • 2014-12-18
    • 1970-01-01
    • 2021-03-22
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多