0
請與你的答案友好我已經編寫了10天。我在代碼中執行循環時遇到了問題,但我相當肯定這是因爲我得到了一個回溯。如何避免除零誤差時,對分析的XML數據執行計算
我解析從URL獲得一個XML文件,使用下面的代碼:
pattern4 = re.compile('title=\'Naps posted: (.*) Winners:')
pattern5 = re.compile('Winners: (.*)\'><img src=')
for row in xmlload1['rows']:
cell = row["cell"]
##### defining the Keys (key is the area from which data is pulled in the XML) for use in the pattern finding/regex
user_delimiter = cell['username']
selection_delimiter = cell['race_horse']
##### the use of the float here is to make sure the result of the strike rate calculations returns as a decimal, otherwise python 2 rounds to the nearest integer!
user_numberofselections = float(re.findall(pattern4, user_delimiter)[0])
user_numberofwinners = float(re.findall(pattern5, user_delimiter)[0])
strikeratecalc1 = user_numberofwinners/user_numberofselections
strikeratecalc2 = strikeratecalc1*100
##### Printing the results of the code at hand
print "number of selections = ",user_numberofselections
print "number of winners = ",user_numberofwinners
print "Strike rate = ",strikeratecalc2,"%"
print ""
getData()
此代碼與代碼返回的休息:
number of selections = 112.0
number of winners = 21.0
Strike rate = 18.75 %
number of selections = 146.0
number of winners = 21.0
Strike rate = 14.3835616438 %
number of selections = 163.0
number of winners = 55.0
Strike rate = 33.7423312883 %
現在這個xmlload的結果提示只有三個用戶可以解析,但是有第四個數據會讀取
number of selections = 0
number of winners = 0
Strike rate = 0
對於我的目的來說,沒有必要爲沒有記錄的用戶提供用戶統計信息,我如何使用0選擇跳過用戶,或者至少使用0來分隔錯誤並不影響代碼在循環中運行?
親切的問候!
感謝您的回答阿什溫,我調整了代碼,我想你一定的意思(與user_numberofselections更換user_numberofwinners)但是代碼仍然返回'ZeroDivisionError:浮動除以零'我重複檢查它是說計算引起錯誤,通過評論它們並打印選擇的數量和贏家數量:'選擇數量= 112.0 獲獎者人數= 21.0 選擇數量= 146.0 獲獎者人數= 21.0 選擇人數ns = 163.0 獲獎者人數= 55.0 選擇人數= 0.0 獲獎者人數= 0.0' – AEA
已修復我的答案。不得不用'is'來比較'float' – Achrome
非常感謝Ashwin,我知道它的基本編碼,但每次我得到這樣的新答案時,它都會增加我的曲目! :) – AEA