批量处理多个文档,支持并行执行
批量处理器是一项面向实际任务的技能,主要用于这种技能可以有效批量处理文档 - 转换、 转换、 提取或分析数百个文件, 并有并行执行和进度 tracki。它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。
实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。
执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
该技能支持高效批量处理文档——可并行执行并跟踪进度,一次性完成数百个文件的格式转换、内容变换、信息抽取或分析任务。
示例提示语:
输入:[file1, file2, ..., fileN]
│
▼
┌─────────────┐
│ 并行工作器 │ ← 并发处理多个文件
│ Parallel │
│ Workers │
└─────────────┘
│
▼
输出:[result1, result2, ..., resultN]
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from tqdm import tqdm
def process_file(file_path: Path) -> dict:
"""处理单个文件。"""
# 此处填写您的具体处理逻辑
return {"path": str(file_path), "status": "success"}
def batch_process(input_dir: str, pattern: str = "*.*", max_workers: int = 4):
"""处理目录中所有匹配的文件。"""
files = list(Path(input_dir).glob(pattern))
results = []
with ProcessPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(process_file, f): f for f in files}
for future in tqdm(as_completed(futures), total=len(files)):
file = futures[future]
try:
result = future.result()
results.append(result)
except Exception as e:
results.append({"path": str(file), "error": str(e)})
return results
# 使用示例
results = batch_process("/documents/invoices", "*.pdf", max_workers=8)
print(f"已处理 {len(results)} 个文件")
import json
from pathlib import Path
class BatchProcessor:
def __init__(self, checkpoint_file: str = "checkpoint.json"):
self.checkpoint_file = checkpoint_file
self.processed = self._load_checkpoint()
def _load_checkpoint(self):
if Path(self.checkpoint_file).exists():
return json.load(open(self.checkpoint_file))
return {}
def _save_checkpoint(self):
json.dump(self.processed, open(self.checkpoint_file, "w"))
def process(self, files: list, processor_func):
for file in files:
if str(file) in self.processed:
continue # 跳过已处理文件
try:
result = processor_func(file)
self.processed[str(file)] = {"status": "success", **result}
except Exception as e:
self.processed[str(file)] = {"status": "error", "error": str(e)}
self._save_checkpoint() # 支持断点续传
# 安装所需依赖 pip install python-docx openpyxl python-pptx reportlab jinja2
相关专题
热门下载
相关下载
精品课程
共6课时 | 54.7万人学习
共89课时 | 133.9万人学习
共49课时 | 82.5万人学习