I've written up a little piece of code that isn't that foolproof to
scan through a file (java presently) to find functions and then look
for them throughout the document and output the name of the function,
followed by how many times it appears and the lines it appears on.
What I was looking for was ways to improve, simplfy and beautify the
code. More to aid my learning of Python than produce a perfect way to
scan for this (netbeans was annoying me...which is why I did this)
Anyway, the source code:
from __future__ import with_statement
functions = dict()
func_words = ("private", "public", "protected")
ignore_class = " class "
def get_func_name(line):
for word in func_words:
if word in line: break
else: return None
# set it to ignore the func_word and the space after
line = line[len(word) + 1:]
index = line.find("(")
if index != -1:
func_name = ""
for letter in reversed(line[:index]):
if letter == " ": break
func_name += letter
return ''.join(reversed(func_name))
else: return None
with open(r"C:\example.java", "r") as test_file:
for number, line in enumerate(test_file):
line = line.strip()
if line.startswith(func_words) and line.find(ignore_class ) ==
-1:
func_name = get_func_name(line);
if func_name is not None:
functions.setdefault(func_name, []).append(number)
test_file.seek(0)
for number, line in enumerate(test_file):
for key in functions.iterkeys():
if line.find(key) != -1:
functions[key].append(number)
print "\n".join("Function: %s, found on %d line(s); these being
%s"
% (k, len(v), v) for k, v in
functions.iteritems())