目标:
提取java代码中的函数信息(函数名、函数返回值、函数返回值类型、函数参数)
思路
1、匹配函数头(public static void name())
正常的函数头都是 以public或private或protected开头——(public|private|protected)+
并不是所有的函数都有static——\s(static)?
函数返回值(字符串)——(\w+)
函数名(字符串)——(\w+)
不同关键词之间含有空格——\s
参数(可有可无,开头必须为字母)——(\w+.*\w*)?
2、匹配返回值变量名
首先只有非void才会有返回值
其次返回值前有 return 关键词
有{}包裹
在前后两个函数之间(提取函数名字之后,利用前后函数名字进行匹配得到)
代码实现
信息提取
#正则表达式匹配method
def process_method(text):
# 构建正则表达式 以public或private或protected开头,中间是几个字母构成的单词,以(参数) 结尾
#(public|private|protected)+ \s(static)?有或者没有static \s?(\w+)\s(\w+)函数名 参数(\w+.*\w*)?
pattern = re.compile(r"(public|private|protected)+\s(static)?\s?(\w+)\s(\w+)\((\w+.*\w*)?\)")
method_info = pattern.findall(text)
count = 1
for method in method_info:
#提取返回值名称
rname = [""]
if method[2]!='void':
#处理最后一个函数
if count >= method_info.__len__():
#re.DOTALL或者re.S可以使.*匹配包括换行符在内的所有字符
pattern = re.compile(r"" + method[3] + "\(.*\).*\s*\{.*return\s(\w+);.*\}", re.S)
else:
pattern = re.compile(r""+method[3]+"\(.*\).*\s*\{.*return\s(\w+);.*\}.*"+method_info[count][3]+"\(.*\)", re.S)
rname = pattern.findall(content)
res = ""
for str in rname:
res = str + "\\" +res
tuple = (res,)
method_info[count-1] = tuple+method_info[count-1]
count = count+1
return method_info
将提取的信息存入Excel
#将method信息存入excel
def saveInExcel(method_info,name,path):
xls = xlwt.Workbook(encoding="utf-8", style_compression=0)
api_sheet = xls.add_sheet(name, cell_overwrite_ok=True)
api_sheet.write(0, 0, "method_name")
api_sheet.write(0, 1, "return_type")
api_sheet.write(0, 2, "return_vname")
api_sheet.write(0, 3, "method_para")
count = 1
for method in method_info:
print(method)
api_sheet.write(count, 0, method[4])
api_sheet.write(count, 1, method[3])
api_sheet.write(count, 2, method[0])
api_sheet.write(count, 3, method[5])
count = count + 1
xls.save(path + name + ".xls")