【发布时间】: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})
【问题讨论】:
-
您好,据我所知,变量
data和print的声明都在第一个for循环中。这是行不通的,因为这样会为每个文件计算、打印和重置data的内容。您应该看到将data的声明移到循环之前,将print的声明移到循环之后。
标签: python python-3.x dictionary for-loop python-requests