I am taking a python course on Coursera side by side with Solo learn and now I'm stuck.
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.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
9/12/2020 7:30:20 AMOsayamen Ebueku
6 AnswersNew Answer
Thanks for all the input... here's my code now. # Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) count = 0 total = 0 for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue total += float(line[20:-1].strip()) count += 1 print("Average spam confidence:", (total/count))
in which part that you're stuck ? how many percent have you done ? can you post the code ?
put every line you found in the array, then get the substring them later to get the float value at the end. if you familar with regex, try lookbehind it save some work by only taking the value at the back
# Using the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue print(line.lstrip("X-DSAPM-Confidence: ")) Now I am having issues adding them up
Which part do you have a problem with? File handling: you have to open it in readonly mode and you can process through each individual line with readline() https://www.w3schools.com/python/python_file_open.asp Detecting the string: you can use regular expressions or str.startswith() And you can convert text to number with the float() method https://www.programiz.com/python-programming/methods/built-in/float
Set a variable before the for loop, where you store the sum. For example total = 0.0 Then inside the loop, you should add the value to the total, where you are printing it currently.. Just convert it to float before you add.