如何避免在对已解析的xml d执行计算时出现零除错误

2024-09-30 18:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

请对你的答案友好我已经编码了10天了。我在代码中执行循环时遇到了问题,但我很确定这是因为我得到了一个回溯。

我使用以下代码解析从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的结果表明只有三个用户需要解析,但是有第四个whos数据需要读取

number of selections =  0
number of winners =  0
Strike rate =  0

就我的目的而言,没有必要为那些没有记录的用户引入用户统计,我如何使代码要么跳过选择为0的用户,要么至少使它不受零除错误的影响,代码在循环中运行的能力?

谨致问候!


Tags: ofthe代码用户inrenumberrate
1条回答
网友
1楼 · 发布于 2024-09-30 18:25:37

找到0时只需使用continue

user_numberofwinners = float(re.findall(pattern5, user_delimiter)[0])

# if the number of winners is 0, go to the next row to avoid division by 0
if user_numberofwinners == 0.0 : continue;

相关问题 更多 >