Python - Counting Words In A Text File

前端 未结 4 2024
悲哀的现实
悲哀的现实 2020-12-10 20:49

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

4条回答
  •  天涯浪人
    2020-12-10 21:25

    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.

提交回复
热议问题