import sys import string command = sys.argv[0] fileName = sys.argv[1] print command inFile = open(fileName) allWords = [] line = inFile.readline() while line: print line newline = line[0:-1] # remove newline words = string.split(newline) allWords = allWords + words line = inFile.readline() # returns empty string at eof inFile.close() freq = {} # Create an empty table for word in allWords: if freq.has_key(word): freq[word] = freq[word] + 1 # any immutable type can be a key else: freq[word] = 1 allKeys = freq.keys() for key in allKeys: print key, '=', freq.get(key) print freq # SAMPLE RUN # a big cat wearing a big hat sat on the big mat #cat = 1 #hat = 1 #the = 1 #big = 3 #mat = 1 #a = 2 #sat = 1 #on = 1 #wearing = 1 #{'cat': 1, 'hat': 1, 'the': 1, 'big': 3, 'mat': 1, 'a': 2, 'sat': 1, #'on': 1, 'wearing': 1}