Reputation: 1590
Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: X-DSPAM-Confidence: 0.8475 Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output
This is my python code
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
inp = fh.read()
count = 0
total = 0
for line in inp:
if not line.strip().startswith("X-DSPAM-Confidence:") : continue
pos = line.find(':')
num = float(line[pos+1:])
total = float(total + num)
count = float(count + 1)
print 'Average spam confidence:', float(total/count)
I don't really know whats going on because i keep getting a zero division error on line 13(last line of the code)
Upvotes: 0
Views: 603
Reputation: 938
Your if
statement is skipping the rest of the for loop because line.strip.startwith("X-DSPAM-Confidence:")
always evaluates to false.
Then, count
is never incremented and thus stays at 0 the whole time, leading to your division by zero error.
Upvotes: 1
Reputation: 5981
What happens when the string X-DSPAM-Confidence:
is not found?
If your code doesn't find that string then the Count var is always zero, so this is one situation where you would get a division by zero error.
Try checking the value of Count before you calculate at the end...
maybe:
If Count>0 print 'Average spam confidence:', float(total/count)
(That may not be the correct python syntax, as I have never used python)
Upvotes: 1
Reputation: 11808
i thing its not reading file properly so it wont be entering the for loop
fh = open(fname)
inp = fh.read()
try this and check if its entering the for
fname = raw_input("Enter file name: ")
fh = open(fname)
inp = fh.read()
count = 0
total = 0
for line in inp:
print inp
Upvotes: 0