doc_translate.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python3
  2. """
  3. 文档翻译辅助工具
  4. - 合并:将多个 MD 文件合并为一个,方便上传翻译
  5. - 还原:将翻译后的文件按标记拆分还原
  6. 用法:
  7. python doc_translate.py merge <源目录> <输出文件>
  8. python doc_translate.py split <翻译后文件> <目标目录>
  9. 示例:
  10. # 合并中文文档
  11. python doc_translate.py merge i18n/zh/documents all_docs_zh.md
  12. # 翻译后还原到英文目录
  13. python doc_translate.py split all_docs_en.md i18n/en/documents
  14. """
  15. import os
  16. import sys
  17. from pathlib import Path
  18. SEPARATOR = "<!-- ===== FILE: {} ===== -->"
  19. def merge(src_dir: str, output_file: str):
  20. """合并目录下所有 MD 文件"""
  21. src_path = Path(src_dir)
  22. files = sorted(src_path.rglob("*.md"))
  23. with open(output_file, "w", encoding="utf-8") as out:
  24. for f in files:
  25. rel_path = f.relative_to(src_path)
  26. out.write(SEPARATOR.format(rel_path) + "\n\n")
  27. out.write(f.read_text(encoding="utf-8"))
  28. out.write("\n\n")
  29. print(f"✅ 合并完成: {len(files)} 个文件 -> {output_file}")
  30. def split(input_file: str, dest_dir: str):
  31. """按标记拆分还原为多个文件"""
  32. dest_path = Path(dest_dir)
  33. content = Path(input_file).read_text(encoding="utf-8")
  34. parts = content.split("<!-- ===== FILE: ")
  35. count = 0
  36. for part in parts[1:]: # 跳过第一个空部分
  37. if " ===== -->" not in part:
  38. continue
  39. header, body = part.split(" ===== -->", 1)
  40. rel_path = header.strip()
  41. file_path = dest_path / rel_path
  42. file_path.parent.mkdir(parents=True, exist_ok=True)
  43. file_path.write_text(body.strip() + "\n", encoding="utf-8")
  44. count += 1
  45. print(f"✅ 还原完成: {input_file} -> {count} 个文件")
  46. if __name__ == "__main__":
  47. if len(sys.argv) < 4:
  48. print(__doc__)
  49. sys.exit(1)
  50. cmd = sys.argv[1]
  51. if cmd == "merge":
  52. merge(sys.argv[2], sys.argv[3])
  53. elif cmd == "split":
  54. split(sys.argv[2], sys.argv[3])
  55. else:
  56. print(f"未知命令: {cmd}")
  57. sys.exit(1)