Created
March 14, 2011 21:10
-
-
Save gpiancastelli/869894 to your computer and use it in GitHub Desktop.
A keyword counter for Python scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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