python - find the occurrence of the word in a file

前端 未结 6 412
自闭症患者
自闭症患者 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:23

    Use the update method of Counter. Example:

    from collections import Counter
    
    data = '''\
    ashwin programmer india
    amith programmer india'''
    
    c = Counter()
    for line in data.splitlines():
        c.update(line.split())
    print(c)
    

    Output:

    Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})
    

提交回复
热议问题