forked from jmelahman/python-for-everybody-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise7_2.py
44 lines (34 loc) · 1.18 KB
/
exercise7_2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
Exercise 7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:
X-DSPAM-Confidence:0.8475
When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.
Enter the file name: mbox.txt
Average spam confidence: 0.894128046745
Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519
Test your file on the mbox.txt and mbox-short.txt files.
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, May 31, 2017
"""
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:',fname)
exit()
count = 0
total = 0
for line in fhand:
if line.startswith('X-DSPAM-Confidence: '):
count = count + 1
colpos = line.find(':')
number = line[colpos+1:].strip() #removes all but number
SPAM_C = float(number)
total = total + SPAM_C
average = total/count
print('Average spam confidence:',average)