0

请善待你的答案,我已经编码了 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 的结果表明只有三个用户要解析但是有第四个谁的数据会读取

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

出于我的目的,没有必要为那些没有跟踪记录的人提取用户统计信息,我如何使代码跳过具有 0 个选择的用户,或者至少使代码除以零错误不会影响循环运行的代码?

亲切的问候!

4

1 回答 1

6

continue找到 0 时只需使用 a 。

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;
于 2013-06-05T02:38:32.200 回答