奇怪的Python Counter问题

时间:2014-04-04 10:33:39

标签: python xml

我试图通过移动设备上的WURFL XML数据进行解析来获取设备ID和大小。解析器似乎正在工作,我正在生成所需的字典和数组。但是,我使用计数器验证我是否为每个设备获得了一整套信息(许多信息不完整),尽管非常简单,但计数器似乎无法正常工作

以下是代码:

import xml.etree.ElementTree as ET

tree = ET.parse('wurfl.xml')

root = tree.getroot()

dicto = {}

for device in root.iter("device"):
    dicto[device.get("id")] = [0, 0, 0, 0]
    for child in device:
        completes = 0 #I'm defining the counter here at the 
                      #beginning of each iteration
        if child.get("id") == "product_info":
            for grand in child:
                if grand.get("name") == "model_name":
                    dicto[device.get("id")][0] = grand.get("value")
                    completes = completes+1 #If I find the first value (product 
                                            #info) count the counter up by 1.
        elif child.get("id") == "display":
            for grand in child:
                if grand.get("name") == "physical_screen_height":
                    dicto[device.get("id")][1] = grand.get("value")
                    completes = completes+1 #count up if you find the height
                elif grand.get("name") == "physical_screen_width":
                    dicto[device.get("id")][2] = grand.get("value")
                    completes = completes+1 #count up if you find the width.
        dicto[device.get("id")][3] = completes #add the count to the array 
                                               #for this key as the final value.

arrays = []

for key in dicto.keys():
    arrays.append(key)

arrays.sort()

这是输出的例子:

#array should print as [product name, height, width, counter].
#For each value (excluding the counter itself) that isn't 0,
#the value of the counter should increase by 1.
>>> dicto[arrays[16481]]
['GT-I9192', 0, 0, 1] #This counter is what is expected
>>> dicto[arrays[16480]]
[0, 0, 0, 0] #This counter is what is expected
>>> dicto[arrays[16477]]
['GT-I9190', '96', '54', 0] #This counter is not what is expected
>>> dicto[arrays[101]]
['A700', '136', '218', 0] #This counter is not what is expected
>>> dicto[arrays[0]]
['Q4350', '94', '57', 2] #This counter is not what is expected

有什么想法吗?

编辑:只是要指出,我将快速进行循环以运行字典键值作为他们的输入,以确保它们被填充,这将有希望工作。但我很困惑为什么我原来的计划没有用。

Edit2:做出我所期望的清晰:

我希望通过检查我是否收集了全部数据(产品信息,高度和宽度)来验证设备。如果解析器找到每条信息,它将按1计数。当我查找3条信息时,一个完整的对象将有一个3的计数器。但是,我找到了一些包含所有3个结果的对象当计数器为0时,计数器为0或2,(计数器由输出数组中的最后一项表示)

Edit3:添加评论

1 个答案:

答案 0 :(得分:1)

您的问题是,您在每个child内迭代多个device人,每次都将completes重置为0。因此,您只能从 last child获取计数。将completes移到该循环之外:

for device in root.iter("device"):
    dicto[device.get("id")] = [0, 0, 0, 0]
    completes = 0
    for child in device:
         ...
    dicto[device.get("id")][3] = completes

或者,当找到每个项目时,抛弃completes并用completes = completes + 1替换completes += 1(可能是dicto[device.get("id")][3] += 1)。