Files
SakuraHub/tools/code_statistics.py
T

228 lines
8.4 KiB
Python
Raw Normal View History

2026-11-16 20:45:22 +08:00
#!/usr/bin/env python3
"""
代码统计与文档生成工具
功能:
1. 统计项目代码数量
2. 生成目录结构
3. 将所有代码保存到docx文档
"""
import os
import re
from docx import Document
from docx.shared import Pt, RGBColor, Cm
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
class CodeStatistics:
"""代码统计类"""
def __init__(self):
self.project_root = '.'
self.exclude_dirs = ('.venv', '.git', '.idea', '__pycache__', 'reports', 'models')
self.exclude_files = ('generate_code_doc.py',)
def analyze(self):
"""执行完整分析"""
print("🔍 正在分析项目代码...")
# 获取项目结构
structure = self._get_structure()
# 统计信息
stats = self._calculate_stats(structure)
# 生成目录树
tree = self._generate_tree(structure)
# 生成文档
self._generate_document(structure, stats, tree)
return stats
def _get_structure(self) -> dict:
"""获取项目结构"""
structure = {}
for root, dirs, files in os.walk(self.project_root):
dirs[:] = [d for d in dirs if d not in self.exclude_dirs]
for f in files:
if f.endswith('.py') and f not in self.exclude_files:
rel_path = os.path.relpath(root, self.project_root)
if rel_path not in structure:
structure[rel_path] = []
structure[rel_path].append(f)
return structure
def _calculate_stats(self, structure: dict) -> dict:
"""计算统计信息"""
stats = {
'files': 0,
'lines': 0,
'functions': 0,
'comments': 0,
'empty_lines': 0,
'size': 0,
'file_details': []
}
for directory, files in structure.items():
for filename in files:
filepath = os.path.join(self.project_root, directory, filename) if directory != '.' else filename
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as fp:
content = fp.read()
lines = content.splitlines()
func_count = len(re.findall(r'^\s*(def|class)\s+', content, re.M))
comment_lines = sum(1 for line in lines if line.strip().startswith('#') or
(line.strip().startswith('"""') or line.strip().startswith("'''")))
empty_lines = sum(1 for line in lines if line.strip() == '')
stats['files'] += 1
stats['lines'] += len(lines)
stats['functions'] += func_count
stats['comments'] += comment_lines
stats['empty_lines'] += empty_lines
stats['size'] += len(content.encode('utf-8'))
stats['file_details'].append({
'name': filename,
'dir': directory,
'lines': len(lines),
'size': len(content.encode('utf-8'))
})
except Exception as e:
print(f"⚠️ 跳过文件: {filename} - {e}")
return stats
def _generate_tree(self, structure: dict) -> str:
"""生成目录树"""
tree = ["📁 SQL注入检测工具"]
for directory, files in sorted(structure.items()):
dir_name = directory if directory != '.' else '根目录'
tree.append(f"├── 📂 {dir_name}")
for filename in sorted(files):
tree.append(f"│ └── 📄 {filename}")
return '\n'.join(tree)
def _generate_document(self, structure: dict, stats: dict, tree: str):
"""生成docx文档"""
print("📝 正在生成文档...")
doc = Document()
# 设置页面边距
for section in doc.sections:
section.top_margin = Cm(2.54)
section.bottom_margin = Cm(2.54)
section.left_margin = Cm(2.54)
section.right_margin = Cm(2.54)
# 标题页
title = doc.add_heading('SQL注入检测工具', level=1)
title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
title.runs[0].font.size = Pt(24)
title.runs[0].font.color.rgb = RGBColor(0, 51, 102)
subtitle = doc.add_heading('项目代码文档', level=2)
subtitle.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
subtitle.runs[0].font.size = Pt(16)
subtitle.runs[0].font.color.rgb = RGBColor(68, 68, 68)
# 目录页
doc.add_page_break()
doc.add_heading('📋 目录', level=1)
idx = 1
for directory, files in sorted(structure.items()):
dir_name = directory if directory != '.' else '根目录'
doc.add_paragraph(f"{idx}. {dir_name}")
jdx = 1
for filename in sorted(files):
doc.add_paragraph(f" {idx}.{jdx} {filename}")
jdx += 1
idx += 1
# 目录结构页
doc.add_page_break()
doc.add_heading('🌳 项目目录结构', level=1)
tree_para = doc.add_paragraph(tree)
tree_para.runs[0].font.name = 'Consolas'
tree_para.runs[0].font.size = Pt(10)
# 统计页
doc.add_page_break()
doc.add_heading('📊 项目统计', level=1)
stats_table = doc.add_table(rows=7, cols=2)
stats_table.style = 'Table Grid'
stats_data = [
('统计项', '数值'),
('Python文件数', str(stats['files'])),
('代码总行数', str(stats['lines'])),
('有效代码行', str(stats['lines'] - stats['empty_lines'])),
('函数/类数量', str(stats['functions'])),
('注释行数', str(stats['comments'])),
('总大小', f"{stats['size'] / 1024:.1f} KB")
]
for row, (label, value) in enumerate(stats_data):
stats_table.rows[row].cells[0].text = label
stats_table.rows[row].cells[1].text = value
# 文件排行
doc.add_heading('📁 文件大小排行', level=2)
sorted_files = sorted(stats['file_details'], key=lambda x: x['size'], reverse=True)[:10]
rank_table = doc.add_table(rows=11, cols=3)
rank_table.style = 'Table Grid'
rank_table.rows[0].cells[0].text = '排名'
rank_table.rows[0].cells[1].text = '文件'
rank_table.rows[0].cells[2].text = '大小(KB)'
for i, file_info in enumerate(sorted_files, 1):
rank_table.rows[i].cells[0].text = str(i)
rank_table.rows[i].cells[1].text = file_info['name']
rank_table.rows[i].cells[2].text = f"{file_info['size'] / 1024:.1f}"
# 代码内容
for directory, files in sorted(structure.items()):
doc.add_page_break()
dir_name = directory if directory != '.' else '根目录'
doc.add_heading(f"📂 {dir_name}", level=1)
for filename in sorted(files):
filepath = os.path.join(self.project_root, directory, filename) if directory != '.' else filename
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as fp:
content = fp.read()
doc.add_heading(f"📄 {filename}", level=2)
doc.add_paragraph("-" * 80)
code_para = doc.add_paragraph()
code_run = code_para.add_run(content)
code_run.font.name = 'Consolas'
code_run.font.size = Pt(9)
doc.add_paragraph()
except Exception as e:
doc.add_paragraph(f"⚠️ 无法读取: {filename} - {e}")
doc.save('下载器项目代码文档.docx')
print("✅ 文档生成完成")
def main():
analyzer = CodeStatistics()
stats = analyzer.analyze()
print("\n" + "=" * 60)
print("📊 项目代码统计结果")
print("=" * 60)
print(f"📄 Python文件数: {stats['files']}")
print(f"📝 代码总行数: {stats['lines']}")
print(f"🔧 函数/类数量: {stats['functions']}")
print(f"📝 注释行数: {stats['comments']}")
print(f"📦 总大小: {stats['size'] / 1024:.1f} KB")
print("=" * 60)
print(f"📄 文档已保存: 下载器项目代码文档.docx")
print("=" * 60)
if __name__ == '__main__':
main()