Advertisement
Gfy

count_groups.py

Gfy
Mar 22nd, 2012
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: latin-1 -*-
  3.  
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18.  
  19. import optparse
  20. import sys
  21. import os
  22. import itertools
  23.  
  24. def main(options, args):
  25.     for element in args:
  26.         element = os.path.abspath(element)
  27.         if os.path.isdir(element):
  28.             start_count(os.listdir(element), options.reverse)
  29.         elif os.path.isfile(element):
  30.             with open(element, 'r') as rellist:
  31.                 start_count(rellist, options.reverse)
  32.         else:
  33.             print("WTF are you supplying me?")
  34.            
  35. def start_count(rellist, reverse):
  36.     cleaned = map(lambda x:  (x.split('-'))[-1], rellist)
  37.     grouped = {}
  38.  
  39.     for (key, elemiter) in itertools.groupby(sorted(cleaned)):
  40.         grouped[key] = sum(1 for _ in elemiter)
  41.    
  42.     # print the results
  43.     for key in sorted(grouped, key=grouped.__getitem__, reverse=reverse):
  44.         print("%3d;%s" % (grouped[key], key))
  45.    
  46. if __name__ == '__main__':
  47.     parser = optparse.OptionParser(
  48.         usage="Usage: %prog [files]'\n"
  49.         "This tool will group groups and list a count based on directories"
  50.         "or a list of releasenames in a text file.\n",
  51.         version="%prog 0.1 (2012-03-22)") # --help, --version
  52.  
  53.     parser.add_option("-r", "--reverse", help="reversed output",
  54.                       action="store_true", dest="reverse", default=False)
  55.    
  56.     # no arguments given
  57.     if len(sys.argv) < 2:
  58.         print(parser.format_help())
  59.     else:
  60.         (options, args) = parser.parse_args()
  61.         main(options, args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement