python - find the occurrence of the word in a file

前端 未结 6 423
自闭症患者
自闭症患者 2020-12-03 22:04

I am trying to find the count of words that occured in a file. I have a text file (TEST.txt) the content of the file is as follows:

ashwin prog         


        
6条回答
  •  被撕碎了的回忆
    2020-12-03 22:40

    You're iterating over every line and calling Counter each time. You want Counter to run over the entire file. Try:

    from collections import Counter
    
    with open("TEST.txt", "r") as f:
        # Used file context read and save into contents
        contents = f.read().split()
    print Counter(contents)
    

提交回复
热议问题