136 lines
4.2 KiB
Python
136 lines
4.2 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
DOCX 转 Markdown 转换器
|
|
使用 mammoth 库将 Word 文档转换为 Markdown 格式
|
|
"""
|
|
|
|
import mammoth
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def docx_to_markdown(docx_path, md_path=None):
|
|
"""
|
|
将 docx 文件转换为 markdown 文件
|
|
|
|
参数:
|
|
docx_path: 输入的 docx 文件路径
|
|
md_path: 输出的 markdown 文件路径(可选,默认为同名 .md 文件)
|
|
|
|
返回:
|
|
转换是否成功 (bool)
|
|
"""
|
|
try:
|
|
# 检查输入文件是否存在
|
|
if not os.path.exists(docx_path):
|
|
print(f"错误: 文件 '{docx_path}' 不存在")
|
|
return False
|
|
|
|
# 检查文件扩展名
|
|
if not docx_path.lower().endswith('.docx'):
|
|
print(f"警告: 文件 '{docx_path}' 可能不是 .docx 格式")
|
|
|
|
# 如果没有指定输出路径,使用同名 .md 文件
|
|
if md_path is None:
|
|
md_path = Path(docx_path).with_suffix('.md')
|
|
|
|
print(f"正在转换: {docx_path} -> {md_path}")
|
|
|
|
# 打开 docx 文件并转换为 markdown
|
|
with open(docx_path, "rb") as docx_file:
|
|
result = mammoth.convert_to_markdown(docx_file)
|
|
markdown_text = result.value
|
|
|
|
# 如果有转换警告,打印出来
|
|
if result.messages:
|
|
print("\n转换警告:")
|
|
for message in result.messages:
|
|
print(f" - {message}")
|
|
|
|
# 保存为 markdown 文件
|
|
with open(md_path, "w", encoding="utf-8") as md_file:
|
|
md_file.write(markdown_text)
|
|
|
|
print(f"✓ 转换成功!输出文件: {md_path}")
|
|
print(f" 文件大小: {len(markdown_text)} 字符")
|
|
return True
|
|
|
|
except Exception as e:
|
|
print(f"✗ 转换失败: {str(e)}")
|
|
return False
|
|
|
|
|
|
def batch_convert(input_dir, output_dir=None):
|
|
"""
|
|
批量转换目录下的所有 docx 文件
|
|
|
|
参数:
|
|
input_dir: 输入目录路径
|
|
output_dir: 输出目录路径(可选,默认为输入目录)
|
|
"""
|
|
if output_dir is None:
|
|
output_dir = input_dir
|
|
|
|
# 确保输出目录存在
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
|
|
# 查找所有 .docx 文件
|
|
docx_files = list(Path(input_dir).glob("*.docx"))
|
|
|
|
if not docx_files:
|
|
print(f"在 '{input_dir}' 目录下没有找到 .docx 文件")
|
|
return
|
|
|
|
print(f"找到 {len(docx_files)} 个 docx 文件\n")
|
|
|
|
success_count = 0
|
|
fail_count = 0
|
|
|
|
for docx_file in docx_files:
|
|
md_file = Path(output_dir) / (docx_file.stem + '.md')
|
|
if docx_to_markdown(str(docx_file), str(md_file)):
|
|
success_count += 1
|
|
else:
|
|
fail_count += 1
|
|
print() # 空行分隔
|
|
|
|
print(f"批量转换完成: 成功 {success_count} 个,失败 {fail_count} 个")
|
|
|
|
|
|
def main():
|
|
"""主函数:处理命令行参数"""
|
|
if len(sys.argv) < 2:
|
|
print("DOCX 转 Markdown 转换器")
|
|
print("\n使用方法:")
|
|
print(" 单文件转换:")
|
|
print(f" python {sys.argv[0]} <input.docx> [output.md]")
|
|
print("\n 批量转换:")
|
|
print(f" python {sys.argv[0]} --batch <input_dir> [output_dir]")
|
|
print("\n示例:")
|
|
print(f" python {sys.argv[0]} document.docx")
|
|
print(f" python {sys.argv[0]} document.docx output.md")
|
|
print(f" python {sys.argv[0]} --batch ./docs ./markdown")
|
|
sys.exit(1)
|
|
|
|
# 批量转换模式
|
|
if sys.argv[1] == "--batch":
|
|
if len(sys.argv) < 3:
|
|
print("错误: 请指定输入目录")
|
|
sys.exit(1)
|
|
input_dir = sys.argv[2]
|
|
output_dir = sys.argv[3] if len(sys.argv) > 3 else input_dir
|
|
batch_convert(input_dir, output_dir)
|
|
|
|
# 单文件转换模式
|
|
else:
|
|
docx_path = sys.argv[1]
|
|
md_path = sys.argv[2] if len(sys.argv) > 2 else None
|
|
|
|
success = docx_to_markdown(docx_path, md_path)
|
|
sys.exit(0 if success else 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |