MRJob - Python - 当除法为0 /值时如何返回null

时间:2013-04-09 14:07:29

标签: python mrjob

如何修改此代码,以便当senti_avg不可分(0 /值)时,reducer()输出NULL或NONE而不是崩溃?

def reducer(self, bs_id, value):
    avg_data = list(value)
    senti_sum = sum([a[0] for a in avg_data])
    word_sum = sum([a[1] for a in avg_data])
    senti_avg = senti_sum/float(word_sum)

    yield (bs_id, senti_avg)

1 个答案:

答案 0 :(得分:4)

您使用python exception handling

try:
    senti_avg = senti_sum/float(word_sum)
except ZeroDivisionError:
    senti_avg = None