Python program that finds most frequent word in a .txt file, Must print word and its count

前端 未结 6 1495
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 23:29

As of right now, I have a function to replace the countChars function,

def countWords(lines):
  wordDict = {}
  for line in lines:
    wordList = lines.split         


        
6条回答
  •  醉话见心
    2020-12-08 00:18

    Here a possible solution, not as elegant as ninjagecko's but still:

    from collections import defaultdict
    
    dicto = defaultdict(int)
    
    with open('yourfile.txt') as f:
        for line in f:
            s_line = line.rstrip().split(',') #assuming ',' is the delimiter
            for ele in s_line:
                dicto[ele] += 1
    
     #dicto contians words as keys, word counts as values
    
     for k,v in dicto.iteritems():
         print k,v
    

提交回复
热议问题