
7-2
By:
Mars83 on
Oct 7th, 2011 | syntax:
Python | size: 1.98 KB | hits: 101 | expires: Never
#! /usr/bin/env python3.2
# -*- coding: utf-8 -*-
# main.py
""" Task: Exercise 7.2
Write a program to prompt for a file name an 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 the 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.
"""
''' Functions '''
def enterFileName():
"""
The user has to enter a filename.
Returns fileName
"""
fileName = None
while fileName == None:
# Enter filename
try:
fileName = input("Enter the filename: ")
except:
print("Invalid input!")
continue
return fileName
# End of enterFileName()
''' Main '''
file = None
totalSpam = 0
spamCounter = 0
spamAverage = 0
fileName = enterFileName()
try:
file = open(fileName, 'r') # Open file
except:
print("File cannot be opened: " + str(fileName))
exit()
if file != None:
try:
for line in file: # Read file content
if line.startswith("X-DSPAM-Confidence:"):
try:
totalSpam += float(line[20:-1])
spamCounter += 1
except:
continue
except:
print("Error on reading file content!")
spamAverage = totalSpam / spamCounter
print("Average spam confidence: " + str(spamAverage))
try:
file.close() # Close file
except:
print("File could not be closed!")
exit()