Skip to content

Instantly share code, notes, and snippets.

@gpiancastelli
Created March 14, 2011 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpiancastelli/869894 to your computer and use it in GitHub Desktop.
Save gpiancastelli/869894 to your computer and use it in GitHub Desktop.
A keyword counter for Python scripts
#!/usr/bin/env python2.6
'''
For each Python script in the current directory, prints the total
number of keywords used and the partial number for each keyword.
'''
import collections
import glob
import keyword
scripts = {}
for script in glob.iglob('*.py'):
results = collections.defaultdict(int)
with open(script) as f:
tokens = [token.strip(':') for line in f
for token in line.split()]
for token in tokens:
if token in keyword.kwlist:
results[token] += 1
scripts[script] = (sum(results.values()), dict(results))
# print statistics for each script
for name, (total, kws) in scripts.items():
print '%s uses %d reserved words:' % (name, total)
print ', '.join('%d %s' % (kws[k], k) for k in sorted(kws))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment