批量将文档转为纯文本脚本

wen 实用脚本 3

本文目录导读:

批量将文档转为纯文本脚本

  1. 脚本:batch_docs_to_txt.py
  2. 安装依赖
  3. 使用方法
  4. 功能特点
  5. 扩展支持

batch_docs_to_txt.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量文档转纯文本工具
支持格式:.txt, .docx, .pdf
"""
import os
import sys
import argparse
from pathlib import Path
# 尝试导入所需库
try:
    import docx  # python-docx
except ImportError:
    docx = None
try:
    import pdfplumber  # 或 PyPDF2
except ImportError:
    pdfplumber = None
def extract_text(file_path):
    """根据文件类型提取文本"""
    suffix = file_path.suffix.lower()
    # 1. 纯文本文件
    if suffix == '.txt':
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return f.read()
        except UnicodeDecodeError:
            # 尝试其他编码
            try:
                with open(file_path, 'r', encoding='gbk') as f:
                    return f.read()
            except:
                return f"[编码错误] {file_path.name}"
    # 2. Word 文档
    elif suffix in ('.docx', '.doc'):
        if docx is None:
            return "[错误] 需要安装 python-docx: pip install python-docx"
        try:
            doc = docx.Document(str(file_path))
            full_text = []
            for para in doc.paragraphs:
                full_text.append(para.text)
            return '\n'.join(full_text)
        except Exception as e:
            return f"[错误] {e}"
    # 3. PDF 文件
    elif suffix == '.pdf':
        if pdfplumber is None:
            # 尝试 PyPDF2 作为备选
            try:
                import PyPDF2
                with open(file_path, 'rb') as f:
                    reader = PyPDF2.PdfReader(f)
                    text = []
                    for page in reader.pages:
                        text.append(page.extract_text())
                    return '\n'.join(text)
            except ImportError:
                return "[错误] 需要安装 pdfplumber 或 PyPDF2"
        try:
            with pdfplumber.open(str(file_path)) as pdf:
                text = []
                for page in pdf.pages:
                    page_text = page.extract_text()
                    if page_text:
                        text.append(page_text)
                return '\n'.join(text)
        except Exception as e:
            return f"[错误] {e}"
    else:
        return f"[不支持格式: {suffix}]"
def convert_file(input_path, output_dir, overwrite=False):
    """转换单个文件"""
    input_path = Path(input_path)
    # 生成输出路径
    output_name = input_path.stem + '.txt'
    output_path = Path(output_dir) / output_name
    # 检查是否已存在
    if output_path.exists() and not overwrite:
        print(f"  跳过 (已存在): {output_name}")
        return False
    # 提取文本
    text = extract_text(input_path)
    if text.startswith("[错误]") or text.startswith("[不支持"):
        print(f"  失败: {input_path.name} - {text}")
        return False
    # 写入文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(text)
    print(f"  ✓ {input_path.name} -> {output_name}")
    return True
def main():
    parser = argparse.ArgumentParser(description='批量文档转纯文本工具')
    parser.add_argument('input', help='输入文件或目录')
    parser.add_argument('-o', '--output', default='output_txt', 
                       help='输出目录 (默认: output_txt)')
    parser.add_argument('--overwrite', action='store_true',
                       help='覆盖已有文件')
    parser.add_argument('--recursive', action='store_true',
                       help='递归处理子目录')
    parser.add_argument('--ext', nargs='+', default=['.txt', '.docx', '.doc', '.pdf'],
                       help='要处理的文件扩展名 (默认: .txt .docx .doc .pdf)')
    args = parser.parse_args()
    input_path = Path(args.input)
    # 检查输入是否存在
    if not input_path.exists():
        print(f"错误: 输入路径不存在: {args.input}")
        sys.exit(1)
    # 创建输出目录
    output_dir = Path(args.output)
    output_dir.mkdir(parents=True, exist_ok=True)
    # 收集要处理的文件
    files_to_process = []
    if input_path.is_file():
        files_to_process.append(input_path)
    elif input_path.is_dir():
        pattern = '*' if args.recursive else '*'
        for ext in args.ext:
            ext_lower = ext.lower()
            if not ext_lower.startswith('.'):
                ext_lower = '.' + ext_lower
            if args.recursive:
                files_to_process.extend(input_path.rglob(f'*{ext_lower}'))
            else:
                files_to_process.extend(input_path.glob(f'*{ext_lower}'))
    if not files_to_process:
        print("没有找到匹配的文件")
        return
    print(f"\n找到 {len(files_to_process)} 个文件")
    print(f"输出目录: {output_dir.resolve()}")
    print("─" * 50)
    success = 0
    fail = 0
    for file_path in sorted(files_to_process):
        if convert_file(file_path, output_dir, args.overwrite):
            success += 1
        else:
            fail += 1
    print("─" * 50)
    print(f"完成: {success} 成功, {fail} 失败")
if __name__ == '__main__':
    # 检查依赖
    missing = []
    if docx is None:
        missing.append("python-docx")
    if pdfplumber is None:
        try:
            import PyPDF2
        except ImportError:
            missing.append("pdfplumber 或 PyPDF2")
    if missing:
        print("缺少依赖:")
        for pkg in missing:
            print(f"  pip install {pkg}")
        print()
    main()

安装依赖

pip install python-docx pdfplumber
# 或 pip install python-docx PyPDF2

使用方法

基本用法

# 转换当前目录所有文档
python batch_docs_to_txt.py .
# 转换单个文件
python batch_docs_to_txt.py document.docx
# 转换指定目录
python batch_docs_to_txt.py /path/to/documents

常用选项

# 递归处理子目录
python batch_docs_to_txt.py . --recursive
# 只处理docx文件
python batch_docs_to_txt.py . --ext .docx
# 指定输出目录
python batch_docs_to_txt.py . -o ./txt_output
# 覆盖已有文件
python batch_docs_to_txt.py . --overwrite

完整示例

# 递归转换当前目录所有文档,输出到my_txt文件夹
python batch_docs_to_txt.py . --recursive -o my_txt
# 转换所有PDF文件
python batch_docs_to_txt.py . --ext pdf
# 指定多种格式
python batch_docs_to_txt.py . --ext docx pdf txt

功能特点

  1. 支持多种格式:docx、doc、pdf、txt
  2. 递归处理--recursive 参数处理子目录
  3. 错误处理:编码错误、格式不支持等都有提示
  4. 进度显示:显示转换成功/失败数量
  5. 避免覆盖:默认跳过已存在的输出文件
  6. 编码自适应:自动处理不同编码的文本文件

扩展支持

如果需要支持更多格式(如 .odt, .rtf),可以修改 extract_text 函数,添加对应的处理逻辑。

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