I am taking a python course on Coursera side by side with Solo learn and now I'm stuck. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

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.

12th Sep 2020, 7:30 AM
Osayamen Ebueku
Osayamen Ebueku - avatar
6 Answers
+ 3
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))
12th Sep 2020, 9:53 AM
Osayamen Ebueku
Osayamen Ebueku - avatar
+ 4
in which part that you're stuck ? how many percent have you done ? can you post the code ?
12th Sep 2020, 7:37 AM
Rei
Rei - avatar
+ 3
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
12th Sep 2020, 8:00 AM
Rei
Rei - avatar
+ 2
# 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
12th Sep 2020, 7:53 AM
Osayamen Ebueku
Osayamen Ebueku - avatar
+ 1
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/JUMP_LINK__&&__python__&&__JUMP_LINK/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
12th Sep 2020, 7:37 AM
Tibor Santa
Tibor Santa - avatar
+ 1
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.
12th Sep 2020, 8:12 AM
Tibor Santa
Tibor Santa - avatar