Advertisement
homer512

Word count

Jan 6th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. #!/usr/bin/python2
  2.  
  3.  
  4. import string
  5. import sys
  6. import collections
  7. import csv
  8.  
  9.  
  10. def main():
  11.     """Counts words (and numbers) in a file"""
  12.     try:
  13.         infilename, outfilename = sys.argv[1:3]
  14.     except IndexError:
  15.         print "Usage: %s INFILE.txt OUTFILE.csv" % sys.argv[0]
  16.         sys.exit(1)
  17.     with open(infilename, 'r') as infile:
  18.         text = infile.read()
  19.     wordstring = text.translate(None, string.punctuation)
  20.     wordlist = wordstring.split()
  21.     counts = collections.Counter(wordlist)
  22.     ordered = counts.most_common()
  23.     with open(outfilename, 'w') as outfile:
  24.         writer = csv.writer(outfile)
  25.         writer.writerows(ordered)
  26.  
  27.  
  28. if __name__ == '__main__':
  29.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement