Python提取函数名与参数后存入字典失败,求解决方法
问题描述
我已经写出了能提取文本中函数名与参数并输出的Python代码:
import re text = ''' def cal_revenue(revenues_store, profit_margin, average_profit): average_profit = revenues_store * profit_margin return average_profit ''' # Extract names lines = text.split('\n') for line in lines: x = re.search(r"^def.*:$", line) if x != None: values = x[0].split('def ')[1].split('(') function_name = values[0] arguments = values[1][:-2].split(', ') print(f"Function Name: {function_name}") print(f"Arguments: {arguments}")
现在想要把提取到的函数名与参数分别存入两个字典,写了下面的代码,但执行后两个字典为空:
# Create dictionaries splited_table1= dict() splited_table2= dict() # Extract names def extraction_variables(text): lines = text.split('\n') for line in lines: x = re.search(r"^def.*:$", line) if x != None: values = x[0].split('def ')[1].split('(') splited_table1 = values[0] splited_table2 = values[1][:-2].split(', ') return splited_table1, splited_table2 extraction_variables(text) splited_table1 splited_table2
请问如何修改代码实现将提取结果存入字典的需求?
问题分析与解决
你的代码存在两个核心问题:
- 变量作用域冲突:函数内部的
splited_table1和splited_table2是局部变量,和外部定义的同名字典没有关联,赋值操作只会修改局部变量,不会影响外部字典。 - 赋值逻辑错误:你直接将字符串(函数名)和列表(参数)赋值给字典变量,这会把字典类型覆盖成普通字符串/列表,而非往字典中存储数据。
以下是两种可行的修改方案:
方案一:用单字典存储函数信息(推荐)
如果需要支持提取多个函数,用一个字典存储更合理——键为函数名,值为对应参数列表:
import re text = ''' def cal_revenue(revenues_store, profit_margin, average_profit): average_profit = revenues_store * profit_margin return average_profit ''' def extraction_variables(text): func_info = {} lines = text.split('\n') for line in lines: # 用正则分组直接提取函数名和参数,处理空格更可靠 match = re.search(r"^def\s+(\w+)\((.*?)\):$", line.strip()) if match: func_name = match.group(1) # 处理参数可能存在的空格,过滤空参数 args = [arg.strip() for arg in match.group(2).split(',') if arg.strip()] func_info[func_name] = args return func_info # 调用函数获取结果 result = extraction_variables(text) print("函数信息字典:", result) # 单独提取函数名和参数列表 func_names = list(result.keys()) args_list = list(result.values())
方案二:存入两个独立字典(按原始需求)
如果必须用两个字典分别存储函数名和参数,可以用索引作为字典的键来对应数据:
import re text = ''' def cal_revenue(revenues_store, profit_margin, average_profit): average_profit = revenues_store * profit_margin return average_profit ''' def extraction_variables(text): func_names = {} func_args = {} index = 0 lines = text.split('\n') for line in lines: match = re.search(r"^def\s+(\w+)\((.*?)\):$", line.strip()) if match: func_name = match.group(1) args = [arg.strip() for arg in match.group(2).split(',') if arg.strip()] func_names[index] = func_name func_args[index] = args index += 1 return func_names, func_args # 调用并接收两个字典 splited_table1, splited_table2 = extraction_variables(text) print("函数名字典:", splited_table1) print("参数字典:", splited_table2)
关键修改说明
- 改用正则分组提取内容,比字符串分割更稳定,能自动处理参数前后的空格。
- 在函数内部创建字典,处理完成后返回结果,彻底避免作用域问题。
- 为字典设置合理的键值对结构,确保数据正确存入字典而非覆盖变量类型。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

