I am having trouble with solving and assignment in which the question asks: "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 as shown below. Do not use the sum() function or a variable named sum in your solution. You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name."
my code is:
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
count = 0
total = 0
#counting lines
for line in fh:
line = line.rstrip()
if not line.startswith("X-DSPAM-Confidence:") :
continue
count = count+1
fcount=float(count)
print fcount
# total spam number thing
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
pos = text.find(':')
slice = text[pos+1:]
fslice = float(slice)
total = fslice + total
ftotal = float(total)
print ftotal
#average
print "Average spam confidence:", (ftotal / fcount)
This code produces the output: 27.0, 0.0, Average Spam Confidence: 0.0
When my code runs, the value for total never increases, so there must be a problem with extracting the strings of numbers after the colon, but instead of getting an error, I am receiving a 0 value. I have run the code block before on a previous assignment in which I was required to extract that floating point value from a string input of that form, so I am guessing the error is coming from how I call for the line from the file.
How can I make this run properly to sum up the floating point values?
Thank you