Python - Counting Words In A Text File

前端 未结 4 2033
悲哀的现实
悲哀的现实 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:37

    What you did looks fine to me, one could also use collections.Counter (assuming you are python 2.7 or newer) to get a bit more information like the number of each word. My solution would look like this, probably some improvement possible.

    import sys
    from collections import Counter
    lines = open(sys.argv[1], 'r').readlines()
    c = Counter()
    for line in lines:
        for work in line.strip().split():
            c.update(work)
    for ind in c:
        print ind, c[ind]
    

提交回复
热议问题