Lecture Notes on 30 October 2009 # This program prompts the use to enter the name of a text file. # It then obtains the frequency of words in that file. def main(): # Prompt user to enter file name and open it file_name = raw_input ("Enter file name: ") inFile = open (file_name, "r") # Create dictionary freq = {} # Read each line and process it for line in inFile: line = line.rstrip("\n") line = line.lower() # Remove punctuation marks line = line.replace(".", "") line = line.replace(",", "") line = line.replace(";", "") line = line.replace(":", "") line = line.replace("?", "") line = line.replace("!", "") line = line.replace("'", "") line = line.replace('"', "") # Split the line into individual words wordList = line.split() # Check each word and increment its count in the dictionary for word in wordList: if (word in freq): freq[word] = freq[word] + 1 else: freq[word] = 1 # Close file inFile.close() # Print frequency of words for word in freq: print word, freq[word] main()