100 个 Agent Skills 盘点(八):文档与文件处理

写在前面
这是「100 个 Agent Skills 盘点」系列的第八篇。这一篇聚焦一个被低估但极其实用的能力:文档与文件处理。
现实世界的数据不都是 JSON 和 CSV。Agent 需要能处理 PDF 报告、Word 文档、Excel 表格、图片等各种格式,才能真正帮助用户处理日常工作。
1. PDF 读取与解析 📄
类别: 文档解析 适用工具: pdf-parse / PyMuPDF / pdfplumber
PDF 是最普遍的文档格式,但也是最难处理的格式之一。Agent 需要能从 PDF 中提取文字、表格和图片。
能力说明:
- 文字提取
- 表格识别和提取
- 图片提取
- 元数据读取
- 页面分割
Agent 使用场景:
# Agent 解析 PDF 合同import pdfplumber
def extract_contract_info(pdf_path): with pdfplumber.open(pdf_path) as pdf: full_text = "" tables = []
for page in pdf.pages: # 提取文字 full_text += page.extract_text() or ""
# 提取表格 page_tables = page.extract_tables() tables.extend(page_tables)
# 用 LLM 分析合同内容 analysis = llm.analyze(f""" 请从以下合同文本中提取关键信息: 1. 合同双方 2. 合同期限 3. 金额 4. 关键条款
文本:{full_text[:5000]} """)
return { "text": full_text, "tables": tables, "analysis": analysis }// Agent 提取 PDF 中的表格数据const pdfParse = require('pdf-parse');const fs = require('fs');
async function extractTablesFromPDF(pdfPath) { const buffer = fs.readFileSync(pdfPath); const data = await pdfParse(buffer);
// 使用正则匹配表格结构 const lines = data.text.split('\n'); const tableData = []; let inTable = false;
for (const line of lines) { if (line.includes('|') || line.match(/\s{3,}/)) { inTable = true; const cells = line.split(/\s{2,}|\|/).filter(Boolean).map(s => s.trim()); tableData.push(cells); } else if (inTable) { inTable = false; } }
return tableData;}典型指令:
读取这份 PDF 报告,提取所有表格数据,转换为 JSON 格式,找出收入最高的三个部门。2. Word 文档处理 📝
类别: 文档处理 适用工具: python-docx / mammoth / docxtemplater
Word 文档是企业环境中最常见的文档格式。Agent 可以读取、生成和修改 Word 文档。
能力说明:
- 文字提取和修改
- 样式处理
- 表格操作
- 图片插入
- 模板填充
Agent 使用场景:
# Agent 生成 Word 报告from docx import Documentfrom docx.shared import Inches, Ptfrom docx.enum.text import WD_ALIGN_PARAGRAPH
def generate_report(data, output_path): doc = Document()
# 标题 title = doc.add_heading('月度运营报告', 0) title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 摘要 doc.add_heading('执行摘要', level=1) doc.add_paragraph(data['summary'])
# 数据表格 doc.add_heading('详细数据', level=1) table = doc.add_table(rows=1, cols=4) table.style = 'Light Grid Accent 1'
# 表头 headers = ['指标', '本月', '上月', '变化'] for i, header in enumerate(headers): table.rows[0].cells[i].text = header
# 数据行 for row_data in data['metrics']: row = table.add_row() for i, value in enumerate(row_data): row.cells[i].text = str(value)
# 图表说明 doc.add_heading('趋势分析', level=1) doc.add_paragraph(data['analysis'])
doc.save(output_path)// Agent 用模板生成合同const docxtemplater = require('docxtemplater');const fs = require('fs');
async function generateContract(templatePath, data) { const content = fs.readFileSync(templatePath, 'binary'); const doc = new docxtemplater(content);
doc.setData({ partyA: data.partyA, partyB: data.partyB, amount: data.amount, startDate: data.startDate, endDate: data.endDate, terms: data.terms });
doc.render(); return doc.getZip().generate({ type: 'nodebuffer' });}典型指令:
读取这份 Word 格式的需求文档,提取所有的功能需求点,生成一个结构化的需求清单(Excel 格式)。3. Excel 表格处理 📊
类别: 电子表格 适用工具: openpyxl / xlsxwriter / SheetJS
Excel 是数据分析和业务报告的标准格式。Agent 可以读取、分析、生成 Excel 文件。
能力说明:
- 读取和写入单元格
- 公式计算
- 图表生成
- 数据透视表
- 样式设置
Agent 使用场景:
# Agent 分析销售数据并生成报告import openpyxlfrom openpyxl.chart import BarChart, Referencefrom openpyxl.styles import Font, PatternFill
def analyze_sales(excel_path): wb = openpyxl.load_workbook(excel_path) ws = wb.active
# 读取数据 sales_data = [] for row in ws.iter_rows(min_row=2, values_only=True): sales_data.append({ 'product': row[0], 'region': row[1], 'amount': row[2], 'quantity': row[3] })
# 按产品汇总 product_summary = {} for item in sales_data: product = item['product'] product_summary[product] = product_summary.get(product, 0) + item['amount']
# 创建报告工作簿 report_wb = openpyxl.Workbook() report_ws = report_wb.active report_ws.title = "销售汇总"
# 写入表头 headers = ['产品', '销售额', '占比'] for col, header in enumerate(headers, 1): cell = report_ws.cell(row=1, column=col, value=header) cell.font = Font(bold=True, color="FFFFFF") cell.fill = PatternFill("solid", fgColor="2563EB")
# 写入数据 total = sum(product_summary.values()) for row, (product, amount) in enumerate(sorted(product_summary.items(), key=lambda x: -x[1]), 2): report_ws.cell(row=row, column=1, value=product) report_ws.cell(row=row, column=2, value=amount) report_ws.cell(row=row, column=3, value=f"{amount/total*100:.1f}%")
# 添加图表 chart = BarChart() chart.title = "产品销售额对比" data = Reference(report_ws, min_col=2, min_row=1, max_row=len(product_summary)+1) categories = Reference(report_ws, min_col=1, min_row=2, max_row=len(product_summary)+1) chart.add_data(data, titles_from_data=True) chart.set_categories(categories) report_ws.add_chart(chart, "E2")
report_wb.save("sales_report.xlsx")典型指令:
读取 sales.xlsx 中的销售数据,按地区和产品汇总,生成带图表的分析报告,找出增长最快和下降最快的产品。4. CSV 数据处理 📈
类别: 数据处理 适用工具: pandas / csv / d3-dsv
CSV 是最简单的结构化数据格式,也是数据交换的通用语言。
能力说明:
- 大文件流式处理
- 数据清洗和转换
- 编码处理(UTF-8 / GBK)
- 数据验证
Agent 使用场景:
# Agent 处理大型 CSV 文件import pandas as pd
def process_large_csv(input_path, output_path): # 分块读取大文件 chunks = pd.read_csv(input_path, chunksize=10000, encoding='utf-8')
results = [] for chunk in chunks: # 数据清洗 chunk = chunk.dropna(subset=['email']) # 删除无邮箱的行 chunk['email'] = chunk['email'].str.lower().str.strip() chunk['amount'] = pd.to_numeric(chunk['amount'], errors='coerce')
# 数据转换 chunk['date'] = pd.to_datetime(chunk['date']) chunk['month'] = chunk['date'].dt.to_period('M')
results.append(chunk)
# 合并所有数据 df = pd.concat(results)
# 分析 summary = df.groupby('month').agg( total_amount=('amount', 'sum'), count=('email', 'count'), unique_users=('email', 'nunique') ).reset_index()
summary.to_csv(output_path, index=False) return summary典型指令:
处理这个 500MB 的 CSV 文件,清洗无效数据,按月汇总,输出分析结果到新的 CSV。5. Markdown 处理 ✍️
类别: 标记语言 适用工具: marked / remark / markdown-it
Markdown 是开发者最常用的文档格式。Agent 可以解析、生成和转换 Markdown 文档。
能力说明:
- Markdown 解析和渲染
- 目录生成
- 格式转换(Markdown → HTML / PDF)
- 批量处理
Agent 使用场景:
// Agent 自动生成文档目录const fs = require('fs');
function generateTOC(markdownContent) { const headings = []; const lines = markdownContent.split('\n');
for (const line of lines) { const match = line.match(/^(#{1,6})\s+(.+)/); if (match) { const level = match[1].length; const title = match[2].trim(); const slug = title .toLowerCase() .replace(/[^\w一-龥]+/g, '-') .replace(/^-|-$/g, '');
headings.push({ level, title, slug }); } }
// 生成目录 let toc = '## 目录\n\n'; for (const heading of headings) { const indent = ' '.repeat(heading.level - 1); toc += `${indent}- [${heading.title}](#${heading.slug})\n`; }
return toc;}
// Agent 批量处理 Markdown 文件const files = fs.readdirSync('./docs').filter(f => f.endsWith('.md'));for (const file of files) { const content = fs.readFileSync(`./docs/${file}`, 'utf-8'); const toc = generateTOC(content); // 在第一个标题后插入目录 const updated = content.replace(/(^# .+$)/m, `$1\n\n${toc}`); fs.writeFileSync(`./docs/${file}`, updated);}典型指令:
扫描 docs/ 目录下所有 Markdown 文件,为每个文件自动生成目录,检查是否有断链(链接到不存在的锚点)。6. 图片处理 🖼️
类别: 多媒体处理 适用工具: Sharp / Pillow / ImageMagick
Agent 可以处理图片——调整大小、添加水印、格式转换、OCR 文字识别。
能力说明:
- 图片缩放和裁剪
- 格式转换(PNG ↔ JPG ↔ WebP)
- 水印添加
- 图片压缩
- OCR 文字识别
Agent 使用场景:
// Agent 批量处理产品图片const sharp = require('sharp');const fs = require('fs');const path = require('path');
async function processProductImages(inputDir, outputDir) { const files = fs.readdirSync(inputDir).filter(f => /\.(jpg|jpeg|png|webp)$/i.test(f) );
for (const file of files) { const inputPath = path.join(inputDir, file); const name = path.parse(file).name;
// 生成多种尺寸 const sizes = [ { width: 1200, suffix: 'large' }, // 产品详情页 { width: 600, suffix: 'medium' }, // 列表页 { width: 300, suffix: 'thumbnail' }, // 缩略图 { width: 100, suffix: 'icon' } // 图标 ];
for (const size of sizes) { await sharp(inputPath) .resize(size.width, null, { withoutEnlargement: true }) .webp({ quality: 80 }) .toFile(path.join(outputDir, `${name}-${size.suffix}.webp`)); }
console.log(`✅ Processed: ${file}`); }}# Agent 用 OCR 提取图片中的文字from PIL import Imageimport pytesseract
def extract_text_from_image(image_path): image = Image.open(image_path) text = pytesseract.image_to_string(image, lang='chi_sim+eng') return text.strip()典型指令:
把 images/ 目录下的所有产品图片调整为 800x600,转换为 WebP 格式,压缩到 100KB 以下,添加右下角水印。7. 音频/视频处理 🎬
类别: 多媒体处理 适用工具: FFmpeg / Whisper
Agent 可以处理音视频——转码、剪辑、提取音频、语音转文字。
能力说明:
- 格式转换
- 音频提取
- 视频剪辑
- 语音转文字(Whisper)
- 字幕生成
Agent 使用场景:
# Agent 用 Whisper 做会议录音转文字import whisper
def transcribe_meeting(audio_path): model = whisper.load_model("medium") result = model.transcribe(audio_path, language="zh")
# 生成带时间戳的文字稿 transcript = "" for segment in result["segments"]: start = format_time(segment["start"]) end = format_time(segment["end"]) text = segment["text"] transcript += f"[{start} → {end}] {text}\n"
# 用 LLM 生成会议纪要 summary = llm.generate(f""" 根据以下会议录音文字稿,生成会议纪要: 1. 会议主题 2. 讨论要点(3-5 个) 3. 决议事项 4. 待办事项及负责人
文字稿:{transcript} """)
return {"transcript": transcript, "summary": summary}# Agent 用 FFmpeg 处理视频# 提取音频ffmpeg -i video.mp4 -vn -acodec pcm_s16le audio.wav
# 剪辑前 30 秒ffmpeg -i video.mp4 -t 30 -c copy clip.mp4
# 压缩视频ffmpeg -i input.mp4 -c:v libx264 -crf 28 -preset fast output.mp4
# 添加字幕ffmpeg -i video.mp4 -vf subtitles=subs.srt output.mp4典型指令:
把这段 2 小时的会议录音转成文字,用 Whisper 识别中文内容,然后生成结构化的会议纪要。8. 数据格式转换 🔄
类别: 格式转换 适用工具: csvtojson / js-yaml / xml2js
数据在不同格式之间转换是常见需求。Agent 可以在 JSON、CSV、YAML、XML 等格式之间自由转换。
能力说明:
- JSON ↔ CSV
- YAML ↔ JSON
- XML ↔ JSON
- Excel ↔ CSV
- 自定义格式转换
Agent 使用场景:
// Agent 批量格式转换const fs = require('fs');const yaml = require('js-yaml');const csvtojson = require('csvtojson');
async function convertFormat(inputPath, fromFormat, toFormat) { let data;
// 读取 switch (fromFormat) { case 'json': data = JSON.parse(fs.readFileSync(inputPath, 'utf-8')); break; case 'yaml': data = yaml.load(fs.readFileSync(inputPath, 'utf-8')); break; case 'csv': data = await csvtojson().fromFile(inputPath); break; }
// 写入 const outputPath = inputPath.replace(`.${fromFormat}`, `.${toFormat}`); switch (toFormat) { case 'json': fs.writeFileSync(outputPath, JSON.stringify(data, null, 2)); break; case 'yaml': fs.writeFileSync(outputPath, yaml.dump(data)); break; case 'csv': const headers = Object.keys(data[0]).join(','); const rows = data.map(row => Object.values(row).join(',')); fs.writeFileSync(outputPath, [headers, ...rows].join('\n')); break; }
console.log(`✅ Converted: ${inputPath} → ${outputPath}`);}典型指令:
把这个 YAML 配置文件转换为 JSON,把那个 CSV 文件转换为 YAML,确保中文编码正确。9. Sentry MCP Server 🐛
类别: 错误监控 协议: MCP(Model Context Protocol)
Sentry 是业界最流行的错误监控平台,通过 MCP 协议,Agent 可以直接查询错误数据、分析堆栈、创建 Issue 并分配负责人,实现从”发现错误”到”修复问题”的全流程自动化。
能力说明:
- 错误追踪:查询项目中的错误事件、异常堆栈和发生频率
- 性能监控:追踪 API 响应时间、数据库慢查询等性能指标
- 告警配置:设置阈值告警,异常发生时自动通知相关人员
- Issue 管理:自动创建、更新、分配和关闭 Sentry Issue
Agent 使用场景:
// Agent 通过 Sentry MCP Server 自动分析错误并创建 Issue// 1. 查询最近 1 小时的错误事件const recentErrors = await mcp.sentry.queryErrors({ project: 'my-web-app', timeRange: '1h', sort: 'frequency', limit: 10,});
// 2. 按错误类型聚合,找出最常见的问题const topIssues = aggregateByType(recentErrors);
for (const issue of topIssues.slice(0, 3)) { // 3. 分析错误堆栈,定位根因 const analysis = await llm.analyze({ prompt: `分析以下错误堆栈,找出根本原因并给出修复建议: 错误类型:${issue.title} 堆栈信息:${issue.stacktrace} 发生次数:${issue.count} 首次出现:${issue.firstSeen}`, });
// 4. 自动创建 GitHub Issue 并关联 Sentry await mcp.github.createIssue({ repo: 'my-org/my-web-app', title: `[Sentry] ${issue.title}`, body: `## 错误分析\n\n${analysis.summary}\n\n` + `## 堆栈信息\n\n\`\`\`\n${issue.stacktrace}\n\`\`\`\n\n` + `## 修复建议\n\n${analysis.suggestion}\n\n` + `> Sentry Issue: ${issue.permalink}`, labels: ['bug', 'sentry', 'auto-created'], assignees: [analysis.suggestedAssignee], });}
console.log(`✅ 已分析 ${recentErrors.length} 个错误,创建了 ${topIssues.length} 个 Issue`);典型指令:
分析最近 1 小时的错误,找出最常见的 3 个问题,为每个问题创建 GitHub Issue,分配给对应的负责人,并在 Issue 中附上错误堆栈和修复建议。10. 文档生成自动化 🤖
类别: 文档自动化 适用工具: 综合
Agent 可以自动化文档生成流程——从代码注释生成 API 文档、从数据生成报告、从模板生成合同。
能力说明:
- API 文档生成(Swagger / TypeDoc)
- 报告模板填充
- 批量文档生成
- 多格式输出
Agent 使用场景:
# Agent 自动生成 API 文档import astimport json
def generate_api_docs(source_code): """从 Python 代码自动生成 API 文档""" tree = ast.parse(source_code) endpoints = []
for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): # 检查是否有路由装饰器 for decorator in node.decorator_list: if isinstance(decorator, ast.Call): if hasattr(decorator.func, 'attr'): method = decorator.func.attr # get, post, put, delete if method in ('get', 'post', 'put', 'delete'): # 提取路径 path = decorator.args[0].value if decorator.args else '/'
# 提取文档字符串 docstring = ast.get_docstring(node) or ''
# 提取参数 params = [] for arg in node.args.args: params.append(arg.arg)
endpoints.append({ 'method': method.upper(), 'path': path, 'function': node.name, 'params': params, 'description': docstring })
# 生成 Markdown 文档 doc = "# API Documentation\n\n" for ep in endpoints: doc += f"## {ep['method']} {ep['path']}\n\n" doc += f"**Function:** `{ep['function']}`\n\n" doc += f"**Parameters:** {', '.join(ep['params'])}\n\n" doc += f"{ep['description']}\n\n---\n\n"
return doc典型指令:
扫描项目中所有 API 路由文件,自动生成 API 文档(Markdown 格式),包含请求参数、响应格式和示例。本篇小结
| # | Skill | 类别 | 难度 | 价值 |
|---|---|---|---|---|
| 1 | PDF 读取解析 | 文档解析 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| 2 | Word 文档处理 | 文档处理 | ⭐⭐ | ⭐⭐⭐⭐ |
| 3 | Excel 表格处理 | 电子表格 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| 4 | CSV 数据处理 | 数据处理 | ⭐ | ⭐⭐⭐⭐ |
| 5 | Markdown 处理 | 标记语言 | ⭐ | ⭐⭐⭐⭐ |
| 6 | 图片处理 | 多媒体 | ⭐⭐ | ⭐⭐⭐⭐ |
| 7 | 音视频处理 | 多媒体 | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| 8 | 数据格式转换 | 格式转换 | ⭐ | ⭐⭐⭐⭐ |
| 9 | Sentry MCP Server | 错误监控 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 10 | 文档生成自动化 | 文档自动化 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
核心观点: 文档处理 Skills 让 Agent 能”读懂”现实世界的文件。一个能解析 PDF、处理 Excel、识别图片文字的 Agent,才能真正帮助用户处理日常工作中的各种文档。
系列导航
- 👈 上一篇: 第七篇:版本控制与协作
- 👉 下一篇: 第九篇:通信与通知集成
支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!