
python统计单个go语言文件类/属性/方法数时仅统计到一个方法
想要统计一个go语言文件中类、属性和方法的数量,可以使用正则表达式匹配文件内容。
统计方法正则表达式错误
在给定的代码中,统计方法的正则表达式为:
立即学习“Python免费学习笔记(深入)”;
method_pattern = re.compile(r'func\s+\((.*?)\)\s+(\w+)\s*\((.*?)\)\s*{')该正则表达式匹配方法的形式是:
func (接收者)(参数列表){返回类型}但实际的go语言方法可能包含多个返回类型,也可能不包含返回类型。因此,正则表达式需要修改为:
method_pattern = re.compile(r'func\s+\((.*?)\)\s+(\w+)\s*\((.*?)\)\s+(.*?)\s*{')修改后的正则表达式将匹配:
func (接收者)(参数列表){多个返回类型/无返回类型}完整代码
修改后的完整代码如下:
import re
def count_go_elements(file_path):
with open(file_path, 'r') as file:
content = file.read()
# 统计结构体
struct_pattern = re.compile(r'type\s+(\w+)\s+struct')
struct_names = struct_pattern.findall(content)
struct_count = len(set(struct_names)) # 使用集合去重
# 统计字段
field_pattern = re.compile(r'(\w+)\s+(\w+)')
fields = field_pattern.findall(content)
field_count = len(fields)
# 统计方法
method_pattern = re.compile(r'func\s+\((.*?)\)\s+(\w+)\s*\((.*?)\)\s+(.*?)\s*{')
methods = method_pattern.findall(content)
method_count = len(methods)
return struct_count, field_count, method_count
# 指定要统计的 Go 语言文件路径
file_path = '/Users/github_repos/kubernetes/pkg/kubelet/config/file_linux.go'
struct_count, field_count, method_count = count_go_elements(file_path)
print(f'结构体数量: {struct_count}')
print(f'字段数量: {field_count}')
print(f'方法数量: {method_count}')以上就是Python正则表达式如何准确统计Go语言文件中的类、属性和方法数量?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号