1. 程式人生 > >利用Python+正則表示式處理java函式

利用Python+正則表示式處理java函式

目標:

提取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")

結果

這裡寫圖片描述