想要统计.go文件内的类、属性、方法的数量:
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*{')
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}')
执行结果为:
结构体数量: 1
字段数量: 121
方法数量: 1
go文件代码如下:可以看到里面不止1个func方法:
package config
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/fsnotify/fsnotify"
"k8s.io/klog/v2"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/flowcontrol"
kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
)
const (
retryPeriod = 1 * time.Second
maxRetryPeriod = 20 * time.Second
)
type retryableError struct {
message string
}
func (e *retryableError) Error() string {
return e.message
}
func (s *sourceFile) startWatch() {
}
func (s *sourceFile) doWatch() error {
}
func (s *sourceFile) produceWatchEvent(e *fsnotify.Event) error {
}
func (s *sourceFile) consumeWatchEvent(e *watchEvent) error {
switch e.eventType {
case podAdd, podModify:
pod, err := s.extractFromFile(e.fileName)
if err != nil {
return fmt.Errorf("can't process config file %q: %v", e.fileName, err)
}
return s.store.Add(pod)
case podDelete:
if objKey, keyExist := s.fileKeyMapping[e.fileName]; keyExist {
pod, podExist, err := s.store.GetByKey(objKey)
if err != nil {
return err
}
if !podExist {
return fmt.Errorf("the pod with key %s doesn't exist in cache", objKey)
}
if err = s.store.Delete(pod); err != nil {
return fmt.Errorf("failed to remove deleted pod from cache: %v", err)
}
delete(s.fileKeyMapping, e.fileName)
}
}
return nil
}
请问这个正则匹配是哪里的问题啊?
method_pattern = re.compile(r'func\s+\((.*?)\)\s+(\w+)\s*\((.*?)\)\s*{')
这样就行了。
