Making code more efficient and effective

Cédric Lucantis omer at no-log.org
Thu Jun 26 09:39:58 EDT 2008


Le Thursday 26 June 2008 14:11:35 cokofreedom at gmail.com, vous avez écrit :
> 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:

I would use some regexp instead (assuming that the function prototype is on a 
single line and that the return type of the function is a single identifier, 
I don't remember if it's always the case in Java)

PAT = re.compile('^[ ]*(public|protected|private)[ ]+([a-zA-Z0-9_]+)
[ ]+([a-zA-Z0-9_]+)[ ]+\((.*)\).*$')

for line in source_file :
    if PAT.match(line) :
        func_vis = PAT.sub(r'\1', line)
        func_type = PAT.sub(r'\2', line)
        func_name = PAT.sub(r'\3', line)
        func_args = PAT.sub(r'\4', line)
        print "'%s' -> '%s' '%s' '%s' '%s'" % (line, func_vis, func_type, 
func_name, func_args)

It might be hard to read but will avoid a lot of obscure parsing code. I can't 
tell if it makes the code more efficient but you don't care about that unless 
you're parsing several million lines of code.

-- 
Cédric Lucantis



More information about the Python-list mailing list