I took the Python class at Google code today, and this is what I made for the problem about building a word counter.
Please take a look and suggest any improvements that can be done. Please do point out the bad practices if I have used any.
import sys
def make_dict(filename):
"""returns a word/count dictionary for the given input file"""
myFile=open(filename,'rU')
text=myFile.read()
words=text.lower().split()
wordcount_dict={} #map each word to its count
for word in words:
wordcount_dict[word]=0
for word in words:
wordcount_dict[word]=wordcount_dict[word]+1
myFile.close()
return wordcount_dict
def print_words(filename):
"""prints each word in the file followed by its count"""
wordcount_dict=make_dict(filename)
for word in wordcount_dict.keys():
print word, " " , wordcount_dict[word]
def print_top(filename):
"""prints the words with the top 20 counts"""
wordcount_dict=make_dict(filename)
keys = wordcount_dict.keys()
values = sorted(wordcount_dict.values())
for x in xrange (1,21): #for the top 20 values
for word in keys :
if wordcount_dict[word]==values[-x]:
print word, " ",wordcount_dict[word]
def main():
if len(sys.argv) != 3:
print 'usage: ./wordcount.py {--count | --topcount} file'
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_words(filename)
elif option == '--topcount':
print_top(filename)
else:
print 'unknown option: ' + option
sys.exit(1)
if __name__ == '__main__':
main()