first commit
This commit is contained in:
commit
b9a3fb9a83
Binary file not shown.
|
After Width: | Height: | Size: 398 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 568 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 732 KiB |
|
|
@ -0,0 +1,101 @@
|
|||
# DOCX 转 Markdown 转换器使用说明
|
||||
|
||||
## 安装依赖
|
||||
|
||||
首先安装所需的 Python 库:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
或者直接安装 mammoth:
|
||||
|
||||
```bash
|
||||
pip install mammoth
|
||||
```
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 1. 单文件转换
|
||||
|
||||
转换单个 docx 文件为 markdown:
|
||||
|
||||
```bash
|
||||
# 自动生成同名 .md 文件
|
||||
python docx_to_md.py document.docx
|
||||
|
||||
# 指定输出文件名
|
||||
python docx_to_md.py document.docx output.md
|
||||
```
|
||||
|
||||
### 2. 批量转换
|
||||
|
||||
批量转换整个目录下的所有 docx 文件:
|
||||
|
||||
```bash
|
||||
# 在同一目录下生成 .md 文件
|
||||
python docx_to_md.py --batch ./documents
|
||||
|
||||
# 指定输出目录
|
||||
python docx_to_md.py --batch ./documents ./markdown_output
|
||||
```
|
||||
|
||||
## 功能特性
|
||||
|
||||
- ✅ 支持标题、段落、列表等基本格式
|
||||
- ✅ 保留文本样式(粗体、斜体等)
|
||||
- ✅ 转换表格为 Markdown 表格格式
|
||||
- ✅ 保留链接
|
||||
- ✅ 支持单文件和批量转换
|
||||
- ✅ 自动生成输出文件名
|
||||
- ✅ 错误处理和转换警告提示
|
||||
|
||||
## 程序化使用
|
||||
|
||||
你也可以在自己的 Python 代码中导入使用:
|
||||
|
||||
```python
|
||||
from docx_to_md import docx_to_markdown, batch_convert
|
||||
|
||||
# 转换单个文件
|
||||
docx_to_markdown('input.docx', 'output.md')
|
||||
|
||||
# 批量转换
|
||||
batch_convert('./input_folder', './output_folder')
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **图片处理**: mammoth 默认不会提取图片,如果需要处理图片,可能需要额外配置
|
||||
2. **复杂格式**: 非常复杂的 Word 格式可能无法完美转换
|
||||
3. **编码问题**: 程序使用 UTF-8 编码保存 markdown 文件
|
||||
|
||||
## 示例输出
|
||||
|
||||
输入 Word 文档:
|
||||
```
|
||||
标题一
|
||||
这是一段普通文本,包含粗体和斜体。
|
||||
```
|
||||
|
||||
输出 Markdown:
|
||||
```markdown
|
||||
# 标题一
|
||||
|
||||
这是一段普通文本,包含**粗体**和*斜体*。
|
||||
```
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 问题:提示 "No module named 'mammoth'"
|
||||
**解决**: 运行 `pip install mammoth` 安装依赖
|
||||
|
||||
### 问题:转换后格式不理想
|
||||
**解决**: mammoth 已经是最好的纯 Python 转换方案,如需更好效果可尝试 pypandoc
|
||||
|
||||
### 问题:中文乱码
|
||||
**解决**: 程序已使用 UTF-8 编码,确保你的终端也支持 UTF-8
|
||||
|
||||
## 许可证
|
||||
|
||||
本程序为示例代码,可自由使用和修改。
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
#!/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()
|
||||
|
|
@ -0,0 +1 @@
|
|||
mammoth>=1.6.0
|
||||
Loading…
Reference in New Issue