Skip to content

Instantly share code, notes, and snippets.

@DrPaulBrewer
Created June 26, 2015 04:09
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 DrPaulBrewer/03ab2051f7ed5a91f1af to your computer and use it in GitHub Desktop.
Save DrPaulBrewer/03ab2051f7ed5a91f1af to your computer and use it in GitHub Desktop.
count expressions in python code, not including comment lines
#!/usr/bin/env python
# Copyright 2015 Paul Brewer
# This file is open source software
# License: The MIT License
import re
import sys
if len(sys.argv)!=3:
print 'Usage: '
print ' python ./code_count.py /path/to/code.py "expression()" '
print " searches for and counts an expression in python code"
print " not including comments" # like this one
print " returns integer count of lines containing the expression "
sys.exit(-1);
(scriptname, codefname, keyword) = sys.argv
code_and_comment_lines = []
with open(codefname,'r') as codefile:
code_and_comment_lines = codefile.readlines()
comment_regex = '(#.*$)'
comment_regex_c = re.compile(comment_regex)
codelines = [comment_regex_c.sub("", l) for l in code_and_comment_lines]
print sum((l.count(keyword) for l in codelines))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment