novel-doomsday-resurgence/tools/apply_title_fixes.py

201 lines
6.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""
自动修复章节标题
"""
import os
import re
import shutil
CHAPTERS_DIR = "/root/.openclaw/workspace/projects/末日重生_囤货/chapters"
# 标题修复映射根据QC报告的建议
TITLE_FIXES = {
# 需要修复的标题
'筹码_手动修复': '致命筹码',
'对峙2': '生死对峙',
'修复': '心灵修复',
# 改进建议(可选修复)
'仓鼠行动': '仓鼠行动', # 可以保持原样
'粮草先行': '粮草先行', # 可以保持原样
'铁壁': '铁壁防线',
'焊花': '焊花飞舞',
'骨刺': '骨刺危机',
'暗流2': '暗流再起',
'质询': '致命质询',
'断水': '水源危机',
'昏沉': '意识迷途',
'电话': '致命来电',
'赴约': '死亡之约',
'充电': '能量重启',
'交付': '生死交付',
'对峙2': '生死对峙',
'决断': '生死决断',
}
def fix_chapter_title(filename, new_title):
"""修复章节标题"""
filepath = os.path.join(CHAPTERS_DIR, filename)
# 读取文件内容
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# 创建备份
backup_path = filepath + '.title.bak'
shutil.copy2(filepath, backup_path)
# 提取原章节号和标题
match = re.search(r'ch(\d+)-第\d+章\s+(.+)\.md', filename)
if not match:
print(f"❌ 无法解析文件名: {filename}")
return False
chapter_num = match.group(1)
old_title = match.group(2)
# 构建新文件名
new_filename = f"ch{chapter_num}-第{chapter_num}{new_title}.md"
new_filepath = os.path.join(CHAPTERS_DIR, new_filename)
# 更新文件内容中的标题
old_header = f"# 第{chapter_num}{old_title}"
new_header = f"# 第{chapter_num}{new_title}"
if old_header in content:
content = content.replace(old_header, new_header, 1)
else:
# 如果标题格式不同,尝试其他匹配方式
lines = content.split('\n')
if lines and lines[0].startswith('# '):
lines[0] = new_header
content = '\n'.join(lines)
# 写入新文件
with open(new_filepath, 'w', encoding='utf-8') as f:
f.write(content)
# 如果文件名改变,删除旧文件
if new_filename != filename:
os.remove(filepath)
return True, new_filename
def main():
print("🔧 章节标题修复系统")
print("=" * 50)
# 获取所有章节文件
chapter_files = [f for f in os.listdir(CHAPTERS_DIR) if f.endswith('.md')]
# 按章节号排序
chapter_files.sort(key=lambda x: int(re.search(r'ch(\d+)', x).group(1)) if re.search(r'ch(\d+)', x) else 0)
print(f"共发现 {len(chapter_files)} 个章节")
print()
# 准备修复列表
files_to_fix = []
for filename in chapter_files:
# 提取原标题
match = re.search(r'ch\d+-第\d+章\s+(.+)\.md', filename)
if not match:
continue
old_title = match.group(1)
# 检查是否需要修复
if old_title in TITLE_FIXES:
new_title = TITLE_FIXES[old_title]
if new_title != old_title: # 只有当标题确实改变时才修复
files_to_fix.append((filename, old_title, new_title))
if not files_to_fix:
print("✅ 所有标题都已是最佳状态,无需修复")
return
print("📋 需要修复的标题:")
print("-" * 60)
for i, (filename, old_title, new_title) in enumerate(files_to_fix, 1):
print(f"{i:2d}. {old_title:15}{new_title}")
print()
print(f"{len(files_to_fix)} 个标题需要修复")
print()
# 确认修复
confirm = input("是否执行修复?(y/N): ").strip().lower()
if confirm != 'y':
print("❌ 修复已取消")
return
print()
print("🔄 开始修复...")
print("-" * 60)
# 执行修复
fixed_count = 0
rename_map = {}
for filename, old_title, new_title in files_to_fix:
print(f"修复: {old_title}{new_title}")
success, new_filename = fix_chapter_title(filename, new_title)
if success:
fixed_count += 1
if new_filename != filename:
rename_map[filename] = new_filename
print(f" ✅ 修复成功")
else:
print(f" ❌ 修复失败")
print()
print("📊 修复完成!")
print(f" 成功修复: {fixed_count}/{len(files_to_fix)}")
if rename_map:
print("\n📁 文件重命名记录:")
for old_name, new_name in rename_map.items():
print(f" {old_name}{new_name}")
# 创建修复日志
create_repair_log(files_to_fix, rename_map, fixed_count)
def create_repair_log(files_to_fix, rename_map, fixed_count):
"""创建修复日志"""
log_path = os.path.join(CHAPTERS_DIR, "../chapter_title_repair_log.md")
with open(log_path, 'w', encoding='utf-8') as f:
f.write("# 章节标题修复日志\n\n")
f.write(f"修复时间: {os.popen('date').read().strip()}\n")
f.write(f"修复章节数: {fixed_count}\n\n")
f.write("## 修复详情\n\n")
f.write("| 原标题 | 新标题 | 状态 |\n")
f.write("|--------|--------|------|\n")
for filename, old_title, new_title in files_to_fix:
status = "✅ 成功" if filename not in rename_map or rename_map[filename] else "❌ 失败"
f.write(f"| {old_title} | {new_title} | {status} |\n")
if rename_map:
f.write("\n## 文件重命名记录\n\n")
f.write("| 原文件名 | 新文件名 |\n")
f.write("|----------|----------|\n")
for old_name, new_name in rename_map.items():
f.write(f"| {old_name} | {new_name} |\n")
f.write("\n## 后续步骤\n\n")
f.write("1. 运行 `git status` 查看文件变化\n")
f.write("2. 运行 `git add chapters/` 添加更改\n")
f.write("3. 运行 `git commit -m '优化章节标题'` 提交\n")
f.write("4. 运行 `git push origin master` 推送到远程\n")
print(f"\n📄 修复日志已保存: {log_path}")
if __name__ == '__main__':
main()