0

How can I modify this code so when senti_avg is not divisible (0/value), reducer() outputs NULL or NONE instead of crashing?

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Nicolas Hung
  • 595
  • 1
  • 6
  • 15

1 Answers1

4

You use python exception handling:

try:
    senti_avg = senti_sum/float(word_sum)
except ZeroDivisionError:
    senti_avg = None
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343