本文目录导读:

使用正则表达式提取
Python 示例
import re
def extract_function(code, function_name):
"""提取指定函数的代码片段"""
# 匹配函数定义开始
pattern = rf"def\s+{function_name}\s*\([^)]*\)\s*:"
start_match = re.search(pattern, code)
if not start_match:
return None
start = start_match.start()
# 找到函数体的结束位置
lines = code[start:].split('\n')
result_lines = [lines[0]]
# 获取函数定义的缩进级别
base_indent = len(lines[0]) - len(lines[0].lstrip())
for line in lines[1:]:
# 检查缩进是否小于基础缩进
current_indent = len(line) - len(line.lstrip())
if line.strip() == '':
result_lines.append(line)
elif current_indent <= base_indent:
break
else:
result_lines.append(line)
return '\n'.join(result_lines)
# 使用示例
script_code = '''
def hello():
print("Hello")
if True:
print("World")
def world():
print("World")
def test():
pass
'''
extracted = extract_function(script_code, "hello")
print(extracted)
使用 AST 解析提取
Python 示例
import ast
import astunparse # 需要安装: pip install astunparse
def extract_function_ast(code, function_name):
"""使用AST提取函数"""
try:
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == function_name:
# 返回函数源代码
return astunparse.unparse(node)
return None
except SyntaxError:
return None
# 使用示例
script_code = """
def hello():
print("Hello")
if True:
print("World")
def world():
print("World")
"""
extracted = extract_function_ast(script_code, "hello")
print(extracted)
基于缩进的通用方法
def extract_function_indent(code, function_name):
"""基于缩进提取函数"""
lines = code.split('\n')
result = []
in_function = False
base_indent = 0
for line in lines:
# 检查是否包含函数定义
if f"def {function_name}(" in line:
in_function = True
base_indent = len(line) - len(line.lstrip())
result.append(line)
continue
if in_function:
# 检查当前行是否仍是函数体
if line.strip() == '':
result.append(line)
continue
current_indent = len(line) - len(line.lstrip())
if current_indent <= base_indent:
break
result.append(line)
return '\n'.join(result) if result else None
命令行工具 (Linux/Mac)
使用 awk
#!/bin/bash
extract_function() {
local file=$1
local func_name=$2
awk -v func="$func_name" '
/^def '"$func_name"'\(/ { flag=1 }
flag { print }
flag && /^[^ ]/ && !/^def/ { flag=0 }
' "$file"
}
# 使用
# extract_function script.py "hello"
跨语言适配
对于不同编程语言,可以调整匹配模式:
import re
def extract_function_generic(code, function_name, language='python'):
"""通用函数提取器"""
patterns = {
'python': rf'def\s+{function_name}\s*\([^)]*\)\s*:',
'javascript': rf'(?:function\s+{function_name}|{function_name}\s*=\s*function)\s*\(',
'java': rf'(?:public|private|protected)?\s*\w+\s+{function_name}\s*\(',
'c': rf'\w+\s+{function_name}\s*\(',
}
pattern = patterns.get(language, patterns['python'])
start_match = re.search(pattern, code)
if not start_match:
return None
# 然后使用大括号或缩进匹配
# ... 实现取决于具体语言
使用建议
- 简单脚本:使用正则表达式方法
- 复杂代码:使用 AST 解析
- 大型文件:考虑逐行读取,节省内存
- 性能要求:使用正则表达式,但要注意复杂度
选择哪种方法取决于你的具体需求和代码的复杂性。