怎么用脚本转换文档结构

wen 实用脚本 1

本文目录导读:

怎么用脚本转换文档结构

  1. Python方案(最通用)
  2. Bash/Shell方案(Linux/Mac)
  3. Node.js方案
  4. 特定格式转换
  5. 实用批处理命令
  6. 选择建议

我来详细介绍几种常见的文档结构转换方法,包括不同场景下的脚本方案。

Python方案(最通用)

安装依赖

pip install python-docx openpyxl pandas PyPDF2 reportlab

基本文档结构转换脚本

import os
from docx import Document
import pandas as pd
class DocumentConverter:
    def __init__(self, input_file):
        self.input_file = input_file
        self.output_dir = "converted_output"
        os.makedirs(self.output_dir, exist_ok=True)
    def docx_to_txt(self):
        """Word转纯文本"""
        doc = Document(self.input_file)
        output_path = os.path.join(self.output_dir, "output.txt")
        with open(output_path, 'w', encoding='utf-8') as f:
            for paragraph in doc.paragraphs:
                f.write(paragraph.text + '\n')
        print(f"转换完成:{output_path}")
        return output_path
    def docx_to_markdown(self):
        """Word转Markdown"""
        doc = Document(self.input_file)
        output_path = os.path.join(self.output_dir, "output.md")
        with open(output_path, 'w', encoding='utf-8') as f:
            for paragraph in doc.paragraphs:
                # 根据样式判断标题级别
                if paragraph.style.name.startswith('Heading'):
                    level = int(paragraph.style.name[-1])
                    f.write('#' * level + ' ' + paragraph.text + '\n\n')
                else:
                    # 检测列表
                    if paragraph.style.name.startswith('List'):
                        f.write('- ' + paragraph.text + '\n')
                    else:
                        f.write(paragraph.text + '\n\n')
        print(f"转换完成:{output_path}")
        return output_path
    def docx_structure_extract(self):
        """提取文档结构(大纲)"""
        doc = Document(self.input_file)
        structure = []
        for paragraph in doc.paragraphs:
            if paragraph.style.name.startswith('Heading'):
                level = int(paragraph.style.name[-1])
                structure.append({
                    'level': level,
                    'text': paragraph.text,
                    'style': paragraph.style.name
                })
        # 保存为CSV
        df = pd.DataFrame(structure)
        output_path = os.path.join(self.output_dir, "structure.csv")
        df.to_csv(output_path, index=False)
        return structure
    def docx_to_json(self, output_format='json'):
        """Word转JSON格式"""
        doc = Document(self.input_file)
        data = {
            'metadata': {
                'file': self.input_file,
                'paragraphs': len(doc.paragraphs),
                'tables': len(doc.tables)
            },
            'content': []
        }
        # 提取段落
        for para in doc.paragraphs:
            if para.text.strip():
                data['content'].append({
                    'type': 'paragraph',
                    'style': para.style.name,
                    'text': para.text
                })
        # 提取表格
        for table in doc.tables:
            table_data = []
            for row in table.rows:
                row_data = [cell.text for cell in row.cells]
                table_data.append(row_data)
            data['content'].append({
                'type': 'table',
                'data': table_data
            })
        # 保存
        if output_format == 'json':
            import json
            output_path = os.path.join(self.output_dir, "output.json")
            with open(output_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        return data
# 使用示例
if __name__ == "__main__":
    converter = DocumentConverter("example.docx")
    # 转换格式
    converter.docx_to_txt()
    converter.docx_to_markdown()
    converter.docx_to_json()
    # 提取结构
    structure = converter.docx_structure_extract()
    print("文档结构:", structure)

Bash/Shell方案(Linux/Mac)

使用Pandoc进行格式转换

#!/bin/bash
# document_converter.sh
# 安装pandoc
# sudo apt-get install pandoc   # Ubuntu
# brew install pandoc           # Mac
# 定义输入输出
INPUT_FILE="$1"
OUTPUT_FORMAT="$2"
convert_document() {
    local input=$1
    local output_format=$2
    local filename=$(basename "$input" .${input##*.})
    case $output_format in
        "txt")
            pandoc "$input" -f docx -t plain -o "${filename}.txt"
            echo "转换为TXT: ${filename}.txt"
            ;;
        "md")
            pandoc "$input" -f docx -t markdown -o "${filename}.md"
            echo "转换为Markdown: ${filename}.md"
            ;;
        "html")
            pandoc "$input" -f docx -t html -o "${filename}.html"
            echo "转换为HTML: ${filename}.html"
            ;;
        "pdf")
            pandoc "$input" -f docx -o "${filename}.pdf"
            echo "转换为PDF: ${filename}.pdf"
            ;;
        "all")
            # 转换为所有格式
            pandoc "$input" -f docx -t plain -o "${filename}.txt"
            pandoc "$input" -f docx -t markdown -o "${filename}.md"
            pandoc "$input" -f docx -t html -o "${filename}.html"
            echo "全部转换完成"
            ;;
        *)
            echo "支持的格式: txt, md, html, pdf, all"
            exit 1
            ;;
    esac
}
# 批量转换目录下所有Word文档
batch_convert() {
    local dir=$1
    local format=$2
    for doc in "$dir"/*.docx; do
        if [ -f "$doc" ]; then
            convert_document "$doc" "$format"
        fi
    done
}
# 主函数
main() {
    if [ $# -lt 2 ]; then
        echo "用法: $0 <输入文件/目录> <输出格式>"
        echo "输出格式: txt, md, html, pdf, all"
        exit 1
    fi
    if [ -d "$1" ]; then
        batch_convert "$1" "$2"
    elif [ -f "$1" ]; then
        convert_document "$1" "$2"
    else
        echo "文件不存在: $1"
        exit 1
    fi
}
main "$@"

使用方式

# 单个文件转换
chmod +x document_converter.sh
./document_converter.sh example.docx md
# 批量转换目录
./document_converter.sh ./docs/ all

Node.js方案

安装依赖

npm install mammoth marked

转换脚本

// document-converter.js
const fs = require('fs');
const path = require('path');
const mammoth = require('mammoth');  // Word转换
const marked = require('marked');      // Markdown渲染
class DocumentConverter {
    constructor() {
        this.outputDir = './converted';
        if (!fs.existsSync(this.outputDir)) {
            fs.mkdirSync(this.outputDir);
        }
    }
    // Word转HTML
    async docxToHtml(inputFile) {
        const result = await mammoth.convertToHtml({
            path: inputFile
        });
        const outputPath = path.join(this.outputDir, 'output.html');
        fs.writeFileSync(outputPath, result.value);
        console.log('HTML转换完成');
        return result.value;
    }
    // Word转Markdown(通过HTML中转)
    async docxToMarkdown(inputFile) {
        const html = await this.docxToHtml(inputFile);
        // 简单HTML转Markdown(实际使用需要更完善的转换)
        const md = html
            .replace(/<h1>/g, '# ')
            .replace(/<h2>/g, '## ')
            .replace(/<h3>/g, '### ')
            .replace(/<\/h[1-3]>/g, '\n\n')
            .replace(/<p>/g, '')
            .replace(/<\/p>/g, '\n\n')
            .replace(/<strong>/g, '**')
            .replace(/<\/strong>/g, '**')
            .replace(/<em>/g, '*')
            .replace(/<\/em>/g, '*')
            .replace(/<[^>]*>/g, '');  // 移除剩余HTML标签
        const outputPath = path.join(this.outputDir, 'output.md');
        fs.writeFileSync(outputPath, md);
        return md;
    }
    // 提取文档结构
    async extractStructure(inputFile) {
        const result = await mammoth.convertToHtml({
            path: inputFile
        });
        const html = result.value;
        const structure = [];
        // 提取标题
        const headingRegex = /<h([1-6])>(.*?)<\/h\1>/g;
        let match;
        while ((match = headingRegex.exec(html)) !== null) {
            structure.push({
                level: parseInt(match[1]),
                text: match[2].replace(/<[^>]*>/g, '')
            });
        }
        // 保存结构
        const outputPath = path.join(this.outputDir, 'structure.json');
        fs.writeFileSync(outputPath, JSON.stringify(structure, null, 2));
        return structure;
    }
}
// 使用示例
async function main() {
    const converter = new DocumentConverter();
    const inputFile = 'example.docx';
    await converter.docxToHtml(inputFile);
    await converter.docxToMarkdown(inputFile);
    await converter.extractStructure(inputFile);
}
main().catch(console.error);

特定格式转换

表格提取脚本

# table_extractor.py
from docx import Document
import csv
def extract_tables(docx_file):
    """提取Word中的表格"""
    doc = Document(docx_file)
    for i, table in enumerate(doc.tables):
        output_file = f"table_{i+1}.csv"
        with open(output_file, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            for row in table.rows:
                writer.writerow([cell.text for cell in row.cells])
        print(f"表格 {i+1} 已保存到 {output_file}")

目录结构生成

# toc_generator.py
from docx import Document
import re
def generate_toc(docx_file):
    """生成目录结构"""
    doc = Document(docx_file)
    toc = []
    for paragraph in doc.paragraphs:
        if paragraph.style.name.startswith('Heading'):
            level = int(re.findall(r'\d+', paragraph.style.name)[0])
            indent = "  " * (level - 1)
            toc.append(f"{indent}{paragraph.text}")
    return '\n'.join(toc)

实用批处理命令

# Linux/Mac批量转换
for file in *.docx; do
    pandoc "$file" -f docx -t markdown -o "${file%.docx}.md"
done
# Windows PowerShell
Get-ChildItem -Filter *.docx | ForEach-Object {
    pandoc $_ -f docx -t markdown -o ($_.BaseName + ".md")
}

选择建议

  1. 简单文本转换:使用Pandoc命令行最快
  2. 结构化提取:Python脚本最灵活
  3. Web应用集成:Node.js方案适合
  4. 批量处理:Shell脚本最适用
  5. 精确控制:Python + python-docx库

需要更具体的转换需求(如特定格式解析、批量处理规则等)?请告诉我你的具体场景。

抱歉,评论功能暂时关闭!