fix_bold_format.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 批量修复Markdown文件中的加粗格式
  5. 将 **文本** 替换为 <strong>文本</strong>
  6. """
  7. import re
  8. import os
  9. import glob
  10. def fix_bold_format_in_file(file_path):
  11. """修复单个文件中的加粗格式"""
  12. try:
  13. with open(file_path, 'r', encoding='utf-8') as f:
  14. content = f.read()
  15. # 先找出所有代码块的位置
  16. code_blocks = []
  17. code_pattern = r'```[\s\S]*?```'
  18. for match in re.finditer(code_pattern, content):
  19. code_blocks.append((match.start(), match.end()))
  20. # 使用正则表达式匹配 **文本** 并替换为 <strong>文本</strong>
  21. # 确保不匹配已经是HTML标签的情况和代码块内的情况
  22. pattern = r'\*\*([^*]+?)\*\*'
  23. def replacement_func(match):
  24. # 检查匹配位置是否在代码块内
  25. match_start = match.start()
  26. for block_start, block_end in code_blocks:
  27. if block_start <= match_start < block_end:
  28. return match.group(0) # 在代码块内,不替换
  29. return f'<strong>{match.group(1)}</strong>' # 不在代码块内,进行替换
  30. # 执行替换
  31. new_content = re.sub(pattern, replacement_func, content)
  32. # 如果内容有变化,写回文件
  33. if new_content != content:
  34. with open(file_path, 'w', encoding='utf-8') as f:
  35. f.write(new_content)
  36. print(f"✅ 已修复: {file_path}")
  37. return True
  38. else:
  39. print(f"ℹ️ 无需修改: {file_path}")
  40. return False
  41. except Exception as e:
  42. print(f"❌ 处理文件出错 {file_path}: {e}")
  43. return False
  44. def main():
  45. """主函数"""
  46. # 查找所有Markdown文件
  47. docs_dir = "D:\code\multiAgentBok\HL-MAS\hello-agents\docs\chapter10"
  48. # 递归查找所有.md文件
  49. md_files = []
  50. for root, dirs, files in os.walk(docs_dir):
  51. for file in files:
  52. if file.endswith('.md'):
  53. md_files.append(os.path.join(root, file))
  54. print(f"找到 {len(md_files)} 个Markdown文件")
  55. print("=" * 50)
  56. modified_count = 0
  57. for file_path in md_files:
  58. if fix_bold_format_in_file(file_path):
  59. modified_count += 1
  60. print("=" * 50)
  61. print(f"处理完成!共修改了 {modified_count} 个文件")
  62. if __name__ == "__main__":
  63. main()