I guess it did not find the string or
Instead of summing the total confidence and counting the amount, you can append to a list or use a generator.
The list knows it's own size. So if you have the list, you have all information you need. The values and the size.
If the list is empty, then don't do the calculation. This safes you against dividing by 0.
fh
is empty.Instead of summing the total confidence and counting the amount, you can append to a list or use a generator.
The list knows it's own size. So if you have the list, you have all information you need. The values and the size.
If the list is empty, then don't do the calculation. This safes you against dividing by 0.
import statistics import io # just to get the data online import requests def get_confidence_avg(fd): """ fd should be a file-like object in text mode or an iterable with str (lines) as elements """ for line in fd: if line.startswith('X-DSPAM-Confidence:'): yield float(line.split(':')[1]) mail_fd = io.StringIO(requests.get('https://www.py4e.com/code3/mbox-short.txt').text) # mail_fd is now a file like object and holds the data from the example # you can use # with open(somefile) as fd: # confidences = list(get_confidence_avg(fd)) confidences = list(get_confidence_avg(mail_fd)) # populating the list with confidence if confidences: mean = statistics.mean(confidences) median = statistics.median(confidences) # or calculating the mean manually mean_manual = sum(confidences) / len(confidences) print('Mean / Mean manual / Median') print(mean, mean_manual, median) else: print('Did not found any match. No information about confidence.')PS: Normally open().read() should work and the fd should be garbage collected afterwards. To be explicit is better. Just use a context-manager or use the modern pathlib. The Path object has the methods
read_text
and read_bytes
. Both methods are using a context manager under the hood.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!