python - find the occurrence of the word in a file

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

    Using a Defaultdict:

    from collections import defaultdict 
    
    def read_file(fname):
    
        words_dict = defaultdict(int)
        fp = open(fname, 'r')
        lines = fp.readlines()
        words = []
    
        for line in lines:
            words += line.split(' ')
    
        for word in words:
            words_dict[word] += 1
    
        return words_dict
    

提交回复
热议问题