Reputation: 33
So I have files of code that contains functions and I need to design a function that will teach through each line of the code and return a list that captures just the function names of the functions in the file. For example, the first file looks like this:
def this_is_a_function():
return 20
def fun():
return 'this is fun!'
Using my function, I should have a list that if printed should return this:
this_is_a_function
fun
Here is the code I have been using:
import re
def get_func_names(filename):
"""doc"""
infile = open(filename)
data = infile.readlines()
result = []
for line in data:
matching = re.search(r'\s*def (\w+)', line)
if matching != None:
result += matching.group(1)
return result
and it does capture all the letters correctly but they are all printed separately rather than as a whole function name like this (this is a printed and sorted version of result):
_
_
_
a
c
f
f
h
i
i
i
n
n
n
o
s
s
t
t
u
u
Is there something I can change about my regex that will capture the name as a while and not each letter and/or underscore....
Upvotes: 2
Views: 252
Reputation: 1537
a += b
when applied to something iterable works like a.extend(b)
, which adds every element of b
to a
.
As strings are iterable, when using +=
Python is taking each element of the string and adding it to the list. Instead, use result.append(matching.group(1))
.
Upvotes: 1