本文将详细介绍如何将Markdown文档转换为Word文档,以及如何将Word文档转换为Markdown格式,帮助您在不同文档格式间轻松切换。
安装 Pandoc:从 Pandoc 官网下载安装包并安装。
转换文件:
pandoc input.md -o output.docx
。pandoc input.docx -o output.md
。以下是一个使用 Python 脚本结合 Pandoc 进行批量转换的示例代码:
# 导入必要的模块
import os # 用于与操作系统交互(如检查文件路径、创建目录等)
import sys # 用于处理命令行参数和退出程序
import subprocess # 用于执行外部命令(如调用Pandoc工具进行文件转换)
def check_args():
"""
检查命令行参数是否正确。
正确的参数格式为:python script.py
"""
# 检查命令行参数的数量是否为4(包括脚本名本身)
if len(sys.argv) != 4:
print("Usage: python script.py " )
sys.exit(1) # 如果参数数量不正确,打印提示信息并退出程序[[2]]
# 获取输入目录、输出目录和操作类型
input_dir = sys.argv[1] # 第一个参数是输入目录
output_dir = sys.argv[2] # 第二个参数是输出目录
operation_type = sys.argv[3] # 第三个参数是操作类型(to_markdown 或 to_word)
# 检查操作类型是否有效
if operation_type not in ['to_markdown', 'to_word']:
print("Error: Invalid operation type. Must be 'to_markdown' or 'to_word'.")
sys.exit(1) # 如果操作类型无效,打印错误信息并退出程序[[2]]
return input_dir, output_dir, operation_type # 返回解析后的参数
def check_directory(directory):
"""
检查给定的目录是否存在。
"""
if not os.path.exists(directory): # 使用os.path.exists检查目录是否存在[[2]]
print(f"Error: Directory '{directory}' does not exist.")
sys.exit(1) # 如果目录不存在,打印错误信息并退出程序
def create_directory(directory):
"""
如果目录不存在,则创建该目录。
"""
if not os.path.exists(directory): # 再次检查目录是否存在
try:
os.makedirs(directory) # 使用os.makedirs创建目录(支持递归创建)
except OSError as e: # 捕获可能的异常(如权限问题)
print(f"Error: Failed to create directory '{directory}'. {e}")
sys.exit(1) # 如果创建失败,打印错误信息并退出程序
def convert_file(input_file, output_file, operation_type):
"""
根据操作类型转换文件。
"""
# 根据操作类型构建Pandoc命令
if operation_type == 'to_markdown':
command = ['pandoc', input_file, '-o', output_file] # 将Word文件转换为Markdown
elif operation_type == 'to_word':
command = ['pandoc', input_file, '-o', output_file, '-s', '--to=docx'] # 将Markdown文件转换为Word文档
try:
# 执行Pandoc命令
result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# check=True会在命令失败时抛出异常,stdout和stderr捕获输出信息
except subprocess.CalledProcessError as e: # 捕获命令执行失败的异常
print(f"Error: Conversion failed for file '{input_file}'. Exit status: {e.returncode}. Output: {e.stderr}")
return False # 如果转换失败,返回False表示操作未成功
return True # 如果转换成功,返回True
def main():
"""
主函数,负责处理文件转换的逻辑。
"""
# 检查命令行参数并获取输入目录、输出目录和操作类型
input_dir, output_dir, operation_type = check_args()
# 检查输入目录是否存在
check_directory(input_dir) # 确保输入目录存在
# 创建输出目录(如果不存在)
create_directory(output_dir) # 确保输出目录存在
# 遍历输入目录中的所有文件
for filename in os.listdir(input_dir): # 使用os.listdir列出目录中的所有文件
input_file = os.path.join(input_dir, filename) # 构建完整的文件路径
if not os.path.isfile(input_file): # 跳过非文件项(如子目录)
continue
# 根据操作类型过滤文件
if operation_type == 'to_markdown' and not filename.endswith('.docx'):
print(f"Warning: Skipping non-Word file '{filename}'.") # 跳过非.docx文件
continue
elif operation_type == 'to_word' and not filename.endswith('.md'):
print(f"Warning: Skipping non-Markdown file '{filename}'.") # 跳过非.md文件
continue
# 构建输出文件路径
output_file = os.path.join(output_dir, os.path.splitext(filename)[0] +
('.md' if operation_type == 'to_markdown' else '.docx')) # 修改文件扩展名
# 调用convert_file进行文件转换
if not convert_file(input_file, output_file, operation_type): # 如果转换失败,跳过当前文件
continue
print(f"Converted '{input_file}' to '{output_file}'.") # 打印成功转换的信息
if __name__ == "__main__":
main() # 当脚本作为主程序运行时,调用main函数
将上述代码保存为.py文件,确保已经正确安装python和pandoc的前提下:
在 Windows 系统中,可以通过以下步骤运行该脚本:
1.打开命令提示符
- 按 Win + R
,输入 cmd
并回车,打开命令提示符。
2.导航到脚本所在目录
假设脚本保存为 script.py
,位于 C:\Users\YourName\Desktop
:
bash cd C:\Users\YourName\Desktop
3. 运行脚本并提供参数
输入以下命令运行脚本:
python script.py path/to/input/directory path/to/output/directory to_markdown
path/to/input/directory
和 path/to/output/directory
为实际路径。在MacOs或Linux中:
1.导航到脚本所在目录:
cd /path/to/script/directory
2.执行脚本并提供参数:
python3 script.py path/to/input/directory path/to/output/directory to_markdown
以下是一个使用 shell 脚本结合 Pandoc 进行批量转换的示例代码:
#!/bin/bash
# 检查参数数量
if [ "$#" -ne 3 ]; then
echo "Usage: $0 "
exit 1
fi
INPUT_DIRECTORY=$1
OUTPUT_DIRECTORY=$2
OPERATION=$3
# 检查操作类型是否有效
if [ "$OPERATION" != "to_markdown" ] && [ "$OPERATION" != "to_word" ]; then
echo "Error: Invalid operation. Use 'to_markdown' or 'to_word'."
exit 1
fi
# 检查输入目录是否存在
if [ ! -d "$INPUT_DIRECTORY" ]; then
echo "Error: Input directory '$INPUT_DIRECTORY' does not exist."
exit 1
fi
# 检查输出目录是否存在,不存在则创建
if [ ! -d "$OUTPUT_DIRECTORY" ]; then
echo "Output directory '$OUTPUT_DIRECTORY' does not exist. Creating..."
mkdir -p "$OUTPUT_DIRECTORY"
if [ $? -ne 0 ]; then
echo "Error: Failed to create output directory '$OUTPUT_DIRECTORY'."
exit 1
fi
fi
# 遍历输入目录下的所有文件
for FILE in "$INPUT_DIRECTORY"/*; do
# 检查文件是否存在
if [ ! -f "$FILE" ]; then
echo "Warning: File '$FILE' does not exist. Skipping..."
continue
fi
# 根据操作类型决定转换方向
if [ "$OPERATION" == "to_markdown" ]; then
# 检查文件是否为Word文档
if [[ "$FILE" == *.docx ]]; then
OUTPUT_FILE="$OUTPUT_DIRECTORY/${FILE##*/}.md"
echo "Converting '$FILE' to '$OUTPUT_FILE'"
pandoc "$FILE" -o "$OUTPUT_FILE"
if [ $? -ne 0 ]; then
echo "Error: Failed to convert '$FILE' to '$OUTPUT_FILE'. Pandoc may not be installed or there may be an issue with the file."
fi
else
echo "Warning: '$FILE' is not a Word document. Skipping..."
fi
elif [ "$OPERATION" == "to_word" ]; then
# 检查文件是否为Markdown文档
if [[ "$FILE" == *.md ]]; then
OUTPUT_FILE="$OUTPUT_DIRECTORY/${FILE##*/}.docx"
echo "Converting '$FILE' to '$OUTPUT_FILE'"
pandoc "$FILE" -o "$OUTPUT_FILE"
if [ $? -ne 0 ]; then
echo "Error: Failed to convert '$FILE' to '$OUTPUT_FILE'. Pandoc may not be installed or there may be an issue with the file."
fi
else
echo "Warning: '$FILE' is not a Markdown document. Skipping..."
fi
fi
done
echo "Conversion completed."
使用方法
chmod +x markdown_word_converter.sh
./markdown_word_converter_with_error_handling.sh /path/to/your/directory to_word
./markdown_word_converter_with_error_handling.sh /path/to/your/directory to_markdown
脚本说明
通过以上分类和步骤,您可以根据自己的需求选择合适的工具进行 Markdown 和 Word 之间的互转。