Python变量名提取问题:函数参数未拆分为独立元素的解决
解决Python函数名与参数提取的拆分问题
问题场景
从给定代码文本中提取函数名及参数时,第一个函数的参数能正常拆分为独立列表元素,但第二个函数的参数因仅用逗号分隔(无空格),导致未被拆分,仍为完整字符串。
问题原因
原代码中使用, (逗号+空格)作为参数分隔符,但部分函数参数仅用逗号分隔,没有空格,导致split(', ')无法正确拆分这类参数。
修改后的代码
import re text = ''' def function_cal_new1 (revenues_stories_new1, surplus_margin_new1, meadian_profit): median_profit= revenues_stories_new1* surplus_margin_new1 return median_profit def cal_tti_c_a(e_BusinessPropertyRightsSuccessor_c,e_Premium_c,e_Interests_c,e_OtherIncome_c,e_PassivelIncome_c,e_SubSubLease_c,estimation_base_BusinessPropertyRights_c,estimation_base_SubLease_c,estimation_base_SubLeaseBusiness_c,estimation_base_SolidWaste_c,estimation_base_Premium_c,estimation_base_PassiveGainsSaleSharePassive_c,estimation_base_PassiveGainsRealEstateThreeYear_c,estimation_base_PassiveGainssaleOtherMovableAssets_c,estimation_base_PassiveGainsSellsRealEstateFiveYear_c,tti_b_a): tti_b_a=e_BusinessPropertyRightsSuccessor_c+e_Premium_c+e_Interests_c+e_OtherIncome_c+e_PassivelIncome_c+e_SubSubLease_c+estimation_base_BusinessPropertyRights_c+estimation_base_SubLease_c+estimation_base_SubLeaseBusiness_c+estimation_base_SolidWaste_c+estimation_base_Premium_c+estimation_base_PassiveGainsSaleSharePassive_c+estimation_base_PassiveGainsRealEstateThreeYear_c+estimation_base_PassiveGainssaleOtherMovableAssets_c+estimation_base_PassiveGainsSellsRealEstateFiveYear_c return(tti_b_a) ''' # Extracting text def extraction_variables(text): lines = text.split('\n') for line in lines: x = re.search(r"^def.*:$", line) if x is not None: values = x[0].split('def ')[1].split('(') splited_table1 = values[0] # 修改参数拆分逻辑:先按逗号分割,再去除每个参数的前后空格,过滤空元素 params_str = values[1][:-2] splited_table2 = [param.strip() for param in params_str.split(',') if param.strip()] yield splited_table1, splited_table2 # Merging extracted text splited_table1, splited_table2 = zip(*extraction_variables(text)) table = [] for elem in splited_table1: table.append(elem) for sub_array in splited_table2: for elem in sub_array: table.append(elem) # Converting in list final_table = list(table) print(final_table)
执行结果
['function_cal_new1 ', 'cal_tti_c_a', 'revenues_stories_new1', 'surplus_margin_new1', 'meadian_profit', 'e_BusinessPropertyRightsSuccessor_c', 'e_Premium_c', 'e_Interests_c', 'e_OtherIncome_c', 'e_PassivelIncome_c', 'e_SubSubLease_c', 'estimation_base_BusinessPropertyRights_c', 'estimation_base_SubLease_c', 'estimation_base_SubLeaseBusiness_c', 'estimation_base_SolidWaste_c', 'estimation_base_Premium_c', 'estimation_base_PassiveGainsSaleSharePassive_c', 'estimation_base_PassiveGainsRealEstateThreeYear_c', 'estimation_base_PassiveGainssaleOtherMovableAssets_c', 'estimation_base_PassiveGainsSellsRealEstateFiveYear_c', 'tti_b_a']
该结果与期望输出完全一致,所有函数名和参数均成为列表的独立元素。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

