【问题标题】:How to sum result of loop for all file xml in python如何在python中对所有文件xml的循环结果求和
【发布时间】:2021-10-14 15:40:25
【问题描述】:

我是编程新手,遇到了问题。 我有 4 个这样的文件

  <object>
    <pose>Damage</pose>
    <pose>Dent</pose>
    <pose>Damage</pose>
    <pose>Dent</pose>
    <pose>Damage</pose>
   </object>

我想计算所有文件中的损坏和凹痕数量。 我已经这样做了,但没有得到我需要的结果。

            import os
            import xml.etree.ElementTree as ET
            from collections import defaultdict
            
            # files are in a sub folder where this script is being ran
            path = r"D:\Non_Documents\xml"
            for filename in os.listdir(path):
                # Only get xml files
                if not filename.endswith('.xml'): continue
                # I haven't been able to get it to work by just saying 'if filename.endswith('.xml')' only if not..
                fullname = os.path.join(path, filename)
                # This joins the path for each file it files so that python knows the full path / filename to trigger parser
                tree = ET.parse(fullname)
                # Parse the files..
                # print(tree)
                data = defaultdict(int)
                # Get the root of the XML tree structure
                root = tree.getroot()
                # print(fullname)
                for name in root.findall('.//name'):
                    data[name.text] += 1
                print(data)

这是我得到的结果

defaultdict(<class 'int'>, { 'Damage': 3, 'Dent': 2})
defaultdict(<class 'int'>, {'Dent': 29, 'Damage': 7})
defaultdict(<class 'int'>, { 'Damage': 6, 'Dent': 15})
defaultdict(<class 'int'>, {'Damage': 7, 'Dent': 19})

我该怎么做才能得到这样的结果?

defaultdict(<class 'int'>, {'Damage': 23, 'Dent': 65})

【问题讨论】:

  • 您好,据我所知,变量dataprint 的声明都在第一个for 循环中。这是行不通的,因为这样会为每个文件计算、打印和重置data 的内容。您应该看到将data 的声明移到循环之前,将print 的声明移到循环之后。

标签: python python-3.x dictionary for-loop python-requests


【解决方案1】:

将你所有的字典添加到下面这样的列表中,

a = [defaultdict(<class 'int'>, { 'Damage': 3, 'Dent': 2}),
defaultdict(<class 'int'>, {'Dent': 29, 'Damage': 7}),
defaultdict(<class 'int'>, { 'Damage': 6, 'Dent': 15}),
defaultdict(<class 'int'>, {'Damage': 7, 'Dent': 19})]

使用下面的代码返回预期的输出,

sumDict = {'Damage': 0, 'Dent': 0}
for i in a:
    for m,n in i.items():
        sumDict.update({m:sumDict[m]+n})

输出将是,

{'Damage': 23, 'Dent': 65}

喜欢的朋友请点赞!!!

【讨论】:

    【解决方案2】:

    我按照您的预期修改了您的代码和确切的结果。你可以试试下面的代码sn-p。

    import os
    import xml.etree.ElementTree as ET
    from collections import defaultdict
    
    # files are in a sub folder where this script is being ran
    path = r"D:\Non_Documents\xml"
    data_list = []
    for filename in os.listdir(path):
        # Only get xml files
        if not filename.endswith('.xml'): continue
        # I haven't been able to get it to work by just saying 'if filename.endswith('.xml')' only if not..
        fullname = os.path.join(path, filename)
        # This joins the path for each file it files so that python knows the full path / filename to trigger parser
        tree = ET.parse(fullname)
        # Parse the files..
        # print(tree)
        data = defaultdict(int)
        # Get the root of the XML tree structure
        root = tree.getroot()
        # print(fullname)
        for name in root.findall('.//name'):
            data[name.text] += 1
        data_list.append(data)
    
    result = defaultdict(int)
    
    for data in data_list:
        for key, value in data.items():
            result[key] += value
    
    print(result)
    

    输出:

    defaultdict(<class 'int'>, {'Damage': 30, 'Dent': 20})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      相关资源
      最近更新 更多