Advertisement
FamiHug

WordCounterVer1.1

Jul 1st, 2012
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. def nice_print(li):
  2.     for i in li:
  3.         print i[1][0] , i[0] ,
  4.         for num in i[1][1:]:
  5.             print num,
  6.         print
  7.  
  8. def count_words(filename):
  9.     fin = open(filename, 'r')
  10.     lines = fin.readlines()
  11.    
  12.     d = {}
  13.    
  14.     #count word and line
  15.     for line in lines:
  16.         line_number = lines.index(line) + 1
  17.         for w in line.split():
  18.             lower = w.lower()
  19.             if lower in d:
  20.                 d[lower][0] += 1
  21.             else:
  22.                                 d[lower] = [1]
  23.             if line_number not in d[lower][1:]:
  24.                 d[lower].append(line_number)
  25.    
  26.     #sort by desc frequency, then by asc word
  27.     sorted_d = sorted(d.iteritems() , key = lambda x: (x[1][0] * -1, x[0]))
  28.     nice_print(sorted_d)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement