Count items and sort by incidence


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. ## {{{ http://code.activestate.com/recipes/52231/ (r1)
  2. class Counter:
  3. def __init__(self):
  4. self.dict = {}
  5. def add(self,item):
  6. count = self.dict.setdefault(item,0)
  7. self.dict[item] = count + 1
  8. def counts(self,desc=None):
  9. '''Returns list of keys, sorted by values.
  10. Feed a 1 if you want a descending sort.'''
  11. i = map(lambda t: list(t),self.dict.items())
  12. map(lambda r: r.reverse(),i)
  13. i.sort()
  14. if desc:
  15. i.reverse()
  16. return i
  17.  
  18. if __name__ == '__main__':
  19.  
  20. '''Produces:
  21.  
  22. >>> Ascending count:
  23. [[1, 'but'], [1, 'it'], [1, 'not.'], [1, 'now'], [1, 'test,'], [1, 'test.'], [1, 'was'], [2, 'Hello'], [2, 'a'], [2, 'is'], [2, 'there'], [2, 'this']]
  24. Descending count:
  25. [[2, 'this'], [2, 'there'], [2, 'is'], [2, 'a'], [2, 'Hello'], [1, 'was'], [1, 'test.'], [1, 'test,'], [1, 'now'], [1, 'not.'], [1, 'it'], [1, 'but']]
  26. '''
  27.  
  28. sentence = "Hello there this is a test. Hello there this was a test, but now it is not."
  29. words = sentence.split()
  30. c=Counter()
  31. for word in words:
  32. c.add(word)
  33. print "Ascending count:"
  34. print c.counts()
  35. print "Descending count:"
  36. print c.counts(1)
  37. ## end of http://code.activestate.com/recipes/52231/ }}}

URL: http://code.activestate.com/recipes/52231-count-items-and-sort-by-incidence/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.