Advertisement
Mars83

7-2

Oct 7th, 2011
1,824
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. #! /usr/bin/env python3.2
  2. # -*- coding: utf-8 -*-
  3.  
  4. # main.py
  5. """ Task: Exercise 7.2
  6.    Write a program to prompt for a file name an then read through the file
  7.    and look for lines of the form:
  8.    X-DSPAM-Confidence: 0.8475
  9.    When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart
  10.    the line to extract the floating point number on the line. Count these
  11.    lines and the compute the total of the spam confidence values from these
  12.    lines. When you reach the end of the file, print out the average spam
  13.    confidence.
  14.    Enter the file name: mbox.txt
  15.    Average spam confidence: 0.894128046745
  16.    Enter the file name: mbox-short.txt
  17.    Average spam confidence: 0.750718518519
  18.    Test your file on the mbox.txt and mbox-short.txt files.
  19. """
  20.  
  21. ''' Functions '''
  22. def enterFileName():
  23.     """
  24.    The user has to enter a filename.
  25.    Returns fileName
  26.    """
  27.     fileName = None
  28.     while fileName == None:
  29.         # Enter filename
  30.         try:
  31.             fileName = input("Enter the filename: ")
  32.         except:
  33.             print("Invalid input!")
  34.             continue
  35.     return fileName
  36. # End of enterFileName()
  37.  
  38. ''' Main '''
  39. file = None
  40. totalSpam = 0
  41. spamCounter = 0
  42. spamAverage = 0
  43. fileName = enterFileName()
  44.  
  45. try:
  46.     file = open(fileName, 'r')      # Open file
  47. except:
  48.     print("File cannot be opened: " + str(fileName))
  49.     exit()
  50. if file != None:
  51.     try:
  52.         for line in file:           # Read file content
  53.             if line.startswith("X-DSPAM-Confidence:"):
  54.                 try:
  55.                     totalSpam += float(line[20:-1])
  56.                     spamCounter += 1
  57.                 except:
  58.                     continue
  59.     except:
  60.        print("Error on reading file content!")
  61.     spamAverage = totalSpam / spamCounter
  62.     print("Average spam confidence: " + str(spamAverage))
  63.     try:
  64.         file.close()                # Close file
  65.     except:
  66.         print("File could not be closed!")
  67.         exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement