I\'m new to Python and am working on a program that will count the instances of words in a simple text file. The program and the text file will be read from the command line
I just noticed a typo: you open the file as f
but you close it as file
. As tripleee said, you shouldn't close files that you open in a with
statement. Also, it's bad practice to use the names of builtin functions, like file
or list
, for your own identifiers. Sometimes it works, but sometimes it causes nasty bugs. And it's confusing for people who read your code; a syntax highlighting editor can help avoid this little problem.
To print the data in your count
dict in descending order of count you can do something like this:
items = count.items()
items.sort(key=lambda (k,v): v, reverse=True)
print '\n'.join('%s: %d' % (k, v) for k,v in items)
See the Python Library Reference for more details on the list.sort() method and other handy dict methods.