我想解析通過移動設備上的WURFL XML數據來獲取設備ID和大小。解析器似乎正在工作,我正在生成所需的字典和數組。然而,我正在使用計數器來驗證每個設備是否有完整的信息(許多信息不完整),儘管非常簡單,但該計數器似乎不起作用。奇怪的Python計數器問題
下面是代碼:
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或2時,他們應爲3(計數器由輸出數組中的最後一個項目代表)
EDIT3:添加評論
究竟是什麼問題?你期望什麼產出? – jonrsharpe
由於數組的每個值都被填充,所以我期望計數器增加。對於任何值(除了數組中的計數器值),值0都表示未找到值。因此,計數器的值應該與數組中不爲0的項數相匹配。因此,第一個示例具有預期結果(填充了1個值,因此計數器== 1)。第二個例子如下。但是第三個和第四個例子有3個值填充了0(它應該是3)的計數器,最後一個有3個值,但計數器是2. – Scironic
請相應地編輯問題,突出顯示問題是什麼以及您會做什麼期望改爲 – jonrsharpe