跳到主要内容
解析 skill-creator:如何编写高质量 AI Skill | 极客日志
Python AI
解析 skill-creator:如何编写高质量 AI Skill 综述由AI生成 基于 Anthropic 官方 skill-creator 仓库,总结了编写高质量 AI Skill 的完整方法论。文章详细解析了 SKILL.md 的结构,包括 YAML 元数据和正文规范,并提炼出七项核心原则:简洁性、自由度匹配、渐进式披露、避免冗余文档、高质量描述、祈使句写作及信息去重。此外,还介绍了 Skill 创建的六个步骤(理解示例、规划内容、初始化、编辑、打包、迭代)以及 Agent Skills 开放标准的目录结构和规范。最后提供了基于 Python 的文档处理 Skill 完整示例,涵盖目录结构、SKILL.md 配置及多个可执行脚本代码。
微码行者 发布于 2026/4/6 更新于 2026/5/21 30 浏览解析 skill-creator:如何编写高质量 AI Skill
本文通过深入分析 Anthropic 官方 skill-creator 代码仓库,提炼出一套编写高质量 Agent Skill 的完整方法论。这些原则适用于 OpenCode、Claude Code、Cursor 等所有支持 Agent Skills 开放标准的 AI 工具。
一、从 skill-creator 仓库我们能学到什么?
1.1 skill-creator 是什么?
skill-creator 是 Anthropic 官方维护的一个 Skill,它的唯一目的就是教 AI 如何创建有效的 Skill 。通过分析这个'教 AI 教 AI'的元 Skill,我们可以获得第一手的最佳实践。
仓库地址:github.com/anthropics/skills/tree/main/skills/skill-creator
1.2 核心文件结构分析
skill-creator/
├── SKILL.md
├── references/
│ ├── output-patterns.md
│ └── workflows.md
└── scripts/
├── init_skill.py
├── package_skill.py
└── quick_validate.py
skill-creator 自身的 SKILL.md 只有 357 行,却涵盖了完整的 Skill 创建方法论。这说明简洁是 Skill 设计的第一原则 。
二、SKILL.md 的核心结构解析
通过分析 skill-creator/SKILL.md 的源码,我们发现一个高质量的 SKILL.md 包含以下部分:
2.1 YAML Frontmatter(元数据头)
---
name: skill-creator
description: |
Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends agent capabilities with specialized knowledge, workflows, or tool integrations.
license: Complete terms in LICENSE.txt
---
name 和 description 是唯一必需的字段
description 必须同时说明'技能做什么'和'何时使用它'
所有'何时使用'的信息必须放在 description 中,因为 body 只在 Skill 触发后才加载
2.2 Body 正文结构
skill-creator 的 SKILL.md 采用以下结构:
正文使用祈使形式(imperative form),直接给出指令而非建议。例如:
'Challenge each piece of information' 质疑每一条信息
'Prefer concise examples over verbose explanations' 用简洁的例子替代冗长的解释
三、从源码提炼的 7 大核心原则
原则 1:上下文窗口是公共资源(Concise is Key)
'The context window is a public good. Skills share the context window with everything else the agent needs: system prompt, conversation history, other Skills' metadata, and the actual user request.'
Skill 与系统提示、对话历史、其他 Skill 元数据、用户请求共享上下文窗口
每个词都要有价值,不断质疑:'AI 真的需要这个解释吗?'
默认假设 AI 已经很智能,只添加它不知道的信息
用简洁示例替代冗长解释
SKILL.md 正文保持在 500 行以内
接近限制时将内容拆分到 references/
原则 2:设置适当的自由度(Degrees of Freedom)
'Match the level of specificity to the task's fragility and variability'
解读: 根据任务的脆弱性和可变性,匹配合适的约束级别:
自由度级别 适用场景 实现方式 高自由度 多种方法有效、依赖上下文决策 文本指令 中自由度 有推荐模式、可接受变化 伪代码或带参数的脚本 低自由度 操作脆弱易错、一致性关键 特定脚本、最少参数
原则 3:渐进式披露设计(Progressive Disclosure)
'Skills use a three-level loading system to manage context efficiently'
┌─────────────────────────────────────────────────────────┐
│ Level 1: 元数据 (name + description) │
│ 始终加载 (~100 tokens) │
├─────────────────────────────────────────────────────────┤
│ Level 2: SKILL.md 正文 │
│ Skill 触发时加载 (< 5000 tokens 推荐) │
├─────────────────────────────────────────────────────────┤
│ Level 3: 捆绑资源 │
│ 按需加载(无限制,脚本可不加载到上下文执行) │
└─────────────────────────────────────────────────────────┘
保持 SKILL.md body 在 500 行以内
拆分时必须从 SKILL.md 清晰引用其他文件
说明何时读取这些文件
原则 4:不要在 Skill 中包含辅助文档 源码原文(What to Not Include in a Skill):
'A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including: README.md, INSTALLATION_GUIDE.md, QUICK_REFERENCE.md, CHANGELOG.md, etc.'
Skill 只应包含 AI Agent 完成工作所需的信息
不应包含创建过程的辅助上下文、设置和测试程序、面向用户的文档
额外的文档只会增加混乱
原则 5:编写高质量的 description
'Only name and description are read by the agent to determine when the skill triggers, so be clear and comprehensive about what the skill is and when it should be used.'
好的 description 示例(来自 docx Skill):
description: |
Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when the agent needs to work with professional documents (.docx files) for:
(1) Creating new documents,
(2) Modifying or editing content,
(3) Working with tracked changes,
(4) Adding comments, or any other document tasks
description: "Helps with PDFs"
同时包含'功能描述'和'触发场景'
所有'何时使用'信息都放在 description 中
Body 只在触发后加载,所以 body 中的'何时使用'对 AI 没有帮助
原则 6:使用祈使/不定式形式 源码原文(Writing Guidelines):
'Always use imperative/infinitive form' (始终使用祈使句/动词原形形式)
'Run the script to check dependencies' (运行该脚本以检查依赖项)
'Extract text using pandoc' (使用 pandoc 提取文本)
'Validate page count before merging PDFs' (在合并 PDF 文件之前先验证页数数量)
'You should run the script to check dependencies' (您应该运行该脚本以检查依赖项)
'We can use pandoc to extract text' (我们可以使用 pandoc 来提取文本)
'I recommend validating the page count' (我建议确认页面数量)
原则 7:避免信息重复
'Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window.'
信息只应存在于一处
详细信息优先放在 references/
SKILL.md 只保留核心程序指令和工作流指导
四、Skill 创建的 6 步流程(源自源码) skill-creator 的 SKILL.md 明确给出了创建 Skill 的 6 个步骤:
步骤 1:通过具体示例理解 Skill
'To create an effective skill, clearly understand concrete examples of how the skill will be used.'
询问:'这个 Skill 应该支持什么功能?'
询问:'你能给出一些使用示例吗?'
询问:'用户会说什么来触发这个 Skill?'
示例: 构建 image-editor Skill 时:
'移除这张图片的红眼'
'将图片旋转 90 度'
'调整图片亮度'
步骤 2:规划可复用的 Skill 内容
'To turn concrete examples into an effective skill, analyze each example by: Considering how to execute on the example from scratch; Identifying what scripts, references, and assets would be helpful'
Skill 类型 示例查询 可复用资源 pdf-editor '帮我旋转这个 PDF' scripts/rotate_pdf.pywebapp-builder '构建一个待办应用' assets/hello-world/模板big-query '今天有多少用户登录?' references/schema.md
步骤 3:初始化 Skill
'When creating a new skill from scratch, always run the init_skill.py script.'
python scripts/init_skill.py <skill-name> --path <output-directory>
创建 Skill 目录
生成带 frontmatter 和 TODO 的 SKILL.md 模板
创建示例资源目录(scripts/、references/、assets/)
步骤 4:编辑 Skill
'When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of the agent to use.'
包含对另一个 AI 实例有益且非明显的信息
考虑什么程序知识、领域细节或可复用资源能帮助另一个 AI 实例更有效地执行这些任务
多步骤流程:参见 references/workflows.md
特定输出格式:参见 references/output-patterns.md
'Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected.'
步骤 5:打包 Skill
'Once development of the skill is complete, it must be packaged into a distributable .skill file'
python scripts/package_skill.py <path/to/skill-folder>[output-dir]
验证 YAML frontmatter 格式和必需字段
验证 Skill 命名约定和目录结构
验证 描述完整性和质量
创建 .skill 文件(zip 格式,.skill 扩展名)
步骤 6:迭代优化
'After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.'
在真实任务中使用 Skill
注意困难或低效的地方
识别 SKILL.md 或资源的更新点
实现更改并再次测试
五、Agent Skills 开放标准
5.1 什么是 Agent Skills? Agent Skills 是一个开放标准 (agentskills.io),最初由 Anthropic 开发,现已被多个 AI 工具采纳:OpenCode,Claude Code,Cursor,GitHub Copilot,Ampcode,trae
5.2 标准规范要点
scripts/ - 可执行代码
references/ - 参考文档
assets/ - 静态资源
---
name: skill-name
description: What this skill does
license: Apache-2.0
compatibility: Requirements
metadata:
author: example-org
version: "1.0"
---
5.3 OpenCode 中的 Skill 存放位置 .opencode/skills/<name>/SKILL.md
.claude/skills/<name>/SKILL.md
.agents/skills/<name>/SKILL.md
~/ .config/opencode/ skills/<name>/ SKILL .md # OpenCode 全局
~/ .claude/skills/ < name>/ SKILL .md # Claude 兼容全局
~/ .agents/skills/ < name>/ SKILL .md # Agents 兼容全局
六、完整示例:文档处理 Skill 基于 skill-creator 的方法论,创建一个 docx-processor Skill:
6.1 目录结构 docx-processor/
├── SKILL.md
├── README.md
├── scripts/
│ ├── extract_text.py
│ ├── add_toc.py
│ └── convert_format.py
├── references/
│ ├── ooxml-reference.md
│ └── formatting-guide.md
└── assets/
└── letterhead-template.docx
6.2 SKILL.md ---
name: docx-processor
description: |
全面的 Word 文档 (.docx) 处理能力,包括文本提取、目录生成、
格式转换、页眉页脚设置。当用户需要处理 Word 文档、创建专业
报告、转换文档格式或提取文档内容时使用。
触发场景:
- 提及 "Word 文档"、".docx"、"docx"
- 请求创建报告、备忘录、信函
- 需要目录、页码、页眉页脚
- 提取或重组文档内容
license: MIT
metadata:
author: your-name
version: "1.0"
---
| 任务 | 方法 |
|-----|------|
| 提取文本 | `python scripts/extract_text.py document.docx` |
| 添加目录 | `python scripts/add_toc.py document.docx` |
| 格式转换 | `python scripts/convert_format.py input.docx output.pdf` |
使用脚本提取纯文本:
`python scripts/extract_text.py document.docx`
输出将保存为 `document.txt`。
运行脚本自动添加目录:
`python scripts/add_toc.py document.docx`
脚本执行步骤:
1 . 扫描文档中的标题
2 . 生成目录结构
3 . 插入到文档开头
输出文件:`document-with-toc.docx`
将 Word 文档转换为 PDF:
`python scripts/convert_format.py input.docx output.pdf`
支持格式:docx → pdf, txt, html
创建带公司信头的新文档:
```python
from docx import Document
doc = Document('assets/letterhead-template.docx')
doc.add_paragraph('正文内容...')
doc.save('output.docx')
高级功能
```python
"""
为 Word 文档添加目录
用法:python add_toc.py <document.docx>
输出:生成带目录的新文档:<原文件名>-with-toc.docx
"""
import sys
from docx import Document
from docx.shared import Pt
def collect_headings (doc: Document ) -> list :
"""收集文档中的所有标题"""
headings = []
for para in doc.paragraphs:
style_name = para.style.name
if style_name.startswith('Heading' ):
try :
level = int (style_name.replace('Heading ' , '' ))
headings.append((level, para.text.strip()))
except ValueError:
continue
return headings
def add_table_of_contents (docx_path: str ) -> str :
"""为 Word 文档添加目录"""
doc = Document(docx_path)
headings = collect_headings(doc)
if not headings:
print ('警告:文档中没有找到标题样式(Heading 1-9)' )
print ('提示:请使用 Word 的标题样式设置章节标题' )
return None
first_para = doc.paragraphs[0 ]
toc_title = first_para.insert_paragraph_before('目录' )
toc_title.style = 'Heading 1'
prev_para = toc_title
for level, text in headings:
indent = ' ' * (level - 1 )
toc_item_text = f'{indent} {text} '
toc_item = prev_para.insert_paragraph_before(toc_item_text)
prev_para = toc_item
prev_para.insert_paragraph_before('' )
output_path = docx_path.replace('.docx' , '-with-toc.docx' )
doc.save(output_path)
return output_path
def main ():
if len (sys.argv) != 2 :
print ('用法:python add_toc.py <document.docx>' )
print ('示例:python add_toc.py report.docx' )
sys.exit(1 )
docx_path = sys.argv[1 ]
try :
output_path = add_table_of_contents(docx_path)
if output_path:
print (f'目录已添加:{output_path} ' )
else :
sys.exit(1 )
except FileNotFoundError:
print (f'错误:找不到文件 {docx_path} ' )
sys.exit(1 )
except Exception as e:
print (f'错误:{e} ' )
sys.exit(1 )
if __name__ == '__main__' :
main()
6.4 scripts/convert_format.py
"""
转换 Word 文档格式
用法:python convert_format.py <input.docx> <output.pdf|txt|html>
支持的输出格式:
- pdf:PDF 文档
- txt:纯文本
- html:网页格式
"""
import sys
import subprocess
import os
def convert_to_pdf (input_path: str , output_path: str ) -> bool :
"""使用 LibreOffice 转换为 PDF"""
try :
cmd = ['soffice' , '--headless' , '--convert-to' , 'pdf' , '--outdir' , os.path.dirname(os.path.abspath(output_path)) or '.' , input_path]
result = subprocess.run(cmd, capture_output=True , text=True )
if result.returncode != 0 :
print (f'转换失败:{result.stderr} ' )
return False
generated_pdf = input_path.replace('.docx' , '.pdf' )
if generated_pdf != output_path and os.path.exists(generated_pdf):
os.rename(generated_pdf, output_path)
return True
except FileNotFoundError:
print ('错误:未找到 LibreOffice (soffice)' )
print ('请安装 LibreOffice:' )
print (' macOS: brew install --cask libreoffice' )
print (' Ubuntu: sudo apt-get install libreoffice' )
return False
def convert_to_txt (input_path: str , output_path: str ) -> bool :
"""使用 pandoc 转换为纯文本"""
try :
cmd = ['pandoc' , input_path, '-o' , output_path]
result = subprocess.run(cmd, capture_output=True , text=True )
if result.returncode != 0 :
print (f'转换失败:{result.stderr} ' )
return False
return True
except FileNotFoundError:
print ('错误:未找到 pandoc' )
print ('请安装 pandoc:https://pandoc.org/installing.html' )
return False
def convert_to_html (input_path: str , output_path: str ) -> bool :
"""使用 pandoc 转换为 HTML"""
try :
cmd = ['pandoc' , input_path, '-o' , output_path, '--standalone' ]
result = subprocess.run(cmd, capture_output=True , text=True )
if result.returncode != 0 :
print (f'转换失败:{result.stderr} ' )
return False
return True
except FileNotFoundError:
print ('错误:未找到 pandoc' )
print ('请安装 pandoc:https://pandoc.org/installing.html' )
return False
def main ():
if len (sys.argv) != 3 :
print ('用法:python convert_format.py <input.docx> <output.pdf|txt|html>' )
print ('示例:' )
print (' python convert_format.py report.docx report.pdf' )
print (' python convert_format.py report.docx report.txt' )
print (' python convert_format.py report.docx report.html' )
sys.exit(1 )
input_path = sys.argv[1 ]
output_path = sys.argv[2 ]
if not os.path.exists(input_path):
print (f'错误:找不到输入文件 {input_path} ' )
sys.exit(1 )
output_ext = os.path.splitext(output_path)[1 ].lower()
success = False
if output_ext == '.pdf' :
success = convert_to_pdf(input_path, output_path)
elif output_ext == '.txt' :
success = convert_to_txt(input_path, output_path)
elif output_ext == '.html' :
success = convert_to_html(input_path, output_path)
else :
print (f'错误:不支持的输出格式 {output_ext} ' )
print ('支持的格式:.pdf, .txt, .html' )
sys.exit(1 )
if success:
print (f'转换成功:{output_path} ' )
else :
sys.exit(1 )
if __name__ == '__main__' :
main()
"""
提取 Word 文档中的文本内容
用法:python extract_text.py <document.docx>
输出:生成与输入文件同名的 .txt 文件
"""
import sys
from docx import Document
def extract_text (docx_path: str ) -> str :
"""从 Word 文档中提取所有文本"""
doc = Document(docx_path)
paragraphs = []
for para in doc.paragraphs:
if para.text.strip():
paragraphs.append(para.text)
tables_text = []
for table in doc.tables:
table_rows = []
for row in table.rows:
row_text = [cell.text.strip() for cell in row.cells]
table_rows.append(' | ' .join(row_text))
tables_text.append('\n' .join(table_rows))
result = '\n\n' .join(paragraphs)
if tables_text:
result += '\n\n=== 表格内容 ===\n\n'
result += '\n\n' .join(tables_text)
return result
def main ():
if len (sys.argv) != 2 :
print ('用法:python extract_text.py <document.docx>' )
print ('示例:python extract_text.py report.docx' )
sys.exit(1 )
docx_path = sys.argv[1 ]
try :
text = extract_text(docx_path)
output_path = docx_path.replace('.docx' , '.txt' )
with open (output_path, 'w' , encoding='utf-8' ) as f:
f.write(text)
print (f'文本已提取:{output_path} ' )
print (f'共 {len (text)} 个字符' )
except FileNotFoundError:
print (f'错误:找不到文件 {docx_path} ' )
sys.exit(1 )
except Exception as e:
print (f'错误:{e} ' )
sys.exit(1 )
if __name__ == '__main__' :
main()
6.6 references/ooxml-reference.md # OOXML 参考指南
本文档提供 Office Open XML (OOXML) 格式的技术参考,用于深度操作 Word 文档。
## 什么是 OOXML?
OOXML 是 Microsoft Office 2007 及以后版本使用的基于 XML 的文档格式。.docx 文件实际上是一个 ZIP 压缩包,包含多个 XML 文件。
## 文档结构
document.docx (ZIP 压缩包)
├── [Content_Types].xml # 内容类型定义
├── _ rels/
│ └── .rels # 包级关系
├── docProps/
│ ├── app.xml # 应用程序属性
│ └── core.xml # 核心属性(作者、标题等)
└── word/
├── document.xml # 文档主要内容
├── styles.xml # 样式定义
├── settings.xml # 文档设置
├── fontTable.xml # 字体表
├── numbering.xml # 编号定义
└── _rels/
└── document.xml.rels # 文档级关系
## 常用操作
### 解压文档
unzip document.docx -d unpacked/
### 重新打包
cd unpacked/
zip -r ../document-new.docx .
## document.xml 结构
### 段落 (Paragraph)
<w:p >
<w:pPr > <!-- 段落属性 -->
<w:pStyle w:val="Heading1"/> <!-- 段落样式 -->
<w:jc w:val="center"/> <!-- 居中对齐 -->
</w:pPr>
<w:r> <!-- 文本运行 -->
<w:rPr> <!-- 文本属性 -->
<w:b/> <!-- 加粗 -->
<w:color w:val="FF0000"/> <!-- 红色 -->
</w:rPr>
<w:t>这是文本内容</w:t> <!-- 文本内容 -->
</w:r>
</w:p>
### 表格 (Table)
<w:tbl >
<w:tblPr > <!-- 表格属性 -->
<w:tblStyle w:val="TableGrid"/>
<w:tblW w:w="5000" w:type="pct"/> <!-- 宽度 5% -->
</w:tblPr>
<w:tr> <!-- 表格行 -->
<w:tc> <!-- 表格单元格 -->
<w:p>
<w:r>
<w:t>单元格内容</w:t>
</w:r>
</w:p>
</w:tc>
</w:tr>
</w:tbl>
## 常用命名空间
| 前缀 | 命名空间 | 说明 |
|-----|---------|------|
| w | http://schemas.openxmlformats.org/wordprocessingml/2006/main | Word 主命名空间 |
| r | http://schemas.openxmlformats.org/officeDocument/2006/relationships | 关系命名空间 |
| wp | http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing | 绘图命名空间 |
## 修订跟踪
### 插入的文本
<w:ins w:id ="1" w:author ="作者名" w:date ="2024-01-01T00:00:00Z" >
<w:r >
<w:t>新插入的文本</w:t>
</w:r>
</w:ins>
### 删除的文本
<w:del w:id ="2" w:author ="作者名" w:date ="2024-01-01T00:00:00Z" >
<w:r >
<w:delText>被删除的文本</w:delText>
</w:r>
</w:del>
## 样式引用
### 段落样式
<w:pStyle w:val ="Heading1" /> <!-- 标题 1 -->
<w:pStyle w:val ="Heading2" /> <!-- 标题 2 -->
<w:pStyle w:val ="Normal" /> <!-- 正文 -->
### 文本样式
<w:rPr >
<w:b /> <!-- 加粗 -->
<w:i /> <!-- 斜体 -->
<w:u w:val ="single" /> <!-- 下划线 -->
<w:strike /> <!-- 删除线 -->
<w:color w:val ="FF0000" /> <!-- 字体颜色 -->
<w:sz w:val ="24" /> <!-- 字号(半磅)12pt -->
<w:rFonts w:ascii ="Arial" /> <!-- 字体 -->
</w:rPr >
## 页眉页脚
### 页眉引用
<w:sectPr >
<w:headerReference w:type ="default" r:id ="rId7" />
</w:sectPr >
### 页脚引用
<w:sectPr >
<w:footerReference w:type ="default" r:id ="rId8" />
<w:pgNumType w:start ="1" /> <!-- 页码从 1 开始 -->
</w:sectPr >
## 参考资料
- [OOXML 标准文档 ](https://ecma-international.org/publications-and-standards/standards/ecma-376/ )
- [python-docx 文档 ](https://python-docx.readthedocs.io/ )
- [Office Open XML 简介 ](https://docs.microsoft.com/en-us/office/open-xml/open-xml-sdk )
6.7 references/formatting-guide.md # 格式化指南
本文档提供 Word 文档格式化的最佳实践和高级技巧。
## 目录
- [样式系统 ](#样式系统 )
- [段落格式 ](#段落格式 )
- [字符格式 ](#字符格式 )
- [列表和编号 ](#列表和编号 )
- [表格格式 ](#表格格式 )
- [修订跟踪 ](#修订跟踪 )
- [评论 ](#评论 )
## 样式系统
### 内置样式
| 样式名称 | 用途 | 级别 |
|---------|------|------|
| Title | 文档标题 | 文档 |
| Heading 1 | 一级标题 | 大纲级别 1 |
| Heading 2 | 二级标题 | 大纲级别 2 |
| Heading 3 | 三级标题 | 大纲级别 3 |
| Normal | 正文 | 正文 |
| Quote | 引用 | 正文 |
| Code | 代码 | 正文 |
### 使用样式的最佳实践
1. **始终使用样式而非直接格式化**
- ❌ 不要:选中文本 → 点击加粗 → 设置字号
- ✅ 要:选中文本 → 应用 "Heading 1" 样式
2. **修改样式而非文本**
- 右键样式 → 修改 → 应用到所有使用该样式的文本
3. **创建自定义样式**
- 样式窗格 → 新建样式 → 定义格式 → 保存
## 段落格式
### 对齐方式
```python
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document()
para = doc.add_paragraph('居中对齐的文本')
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 其他选项:
# WD_ALIGN_PARAGRAPH.LEFT # 左对齐
# WD_ALIGN_PARAGRAPH.RIGHT # 右对齐
# WD_ALIGN_PARAGRAPH.JUSTIFY # 两端对齐
行距和段间距 from docx.shared import Pt
para = doc.add_paragraph('示例段落' )
para.paragraph_format.line_spacing = 1.5
para.paragraph_format.space_before = Pt(12 )
para.paragraph_format.space_after = Pt(12 )
缩进 from docx.shared import Inches
para = doc.add_paragraph('首行缩进的段落' )
para.paragraph_format.first_line_indent = Inches(0.5 )
para.paragraph_format.left_indent = Inches(0.5 )
para.paragraph_format.right_indent = Inches(0.5 )
字符格式
字体设置 from docx.shared import Pt
para = doc.add_paragraph()
run = para.add_run('格式化的文本' )
run.bold = True
run.italic = True
run.underline = True
run.font.size = Pt(12 )
run.font.name = 'Arial'
run.font.color.rgb = RGBColor(255 , 0 , 0 )
中文字体 from docx.oxml.ns import qn
run = para.add_run('中文文本' )
run.font.name = 'SimSun'
run._element.rPr.rFonts.set (qn('w:eastAsia' ), '宋体' )
列表和编号
项目符号列表 doc.add_paragraph('项目 1' ,)
doc.add_paragraph('项目 2' ,)
doc.add_paragraph('项目 3' ,)
编号列表 doc.add_paragraph('第一步' ,)
doc.add_paragraph('第二步' ,)
doc.add_paragraph('第三步' ,)
多级列表
doc.add_paragraph('第一章' ,)
doc.add_paragraph('1.1 节' ,)
doc.add_paragraph('1.2 节' ,)
doc.add_paragraph('1.2.1 小节' ,)
表格格式
创建表格 from docx import Document
from docx.shared import Inches
doc = Document()
table = doc.add_table(rows=3 , cols=3 )
table.style = 'Light Grid Accent 1'
table.columns[0 ].width = Inches(1.5 )
table.columns[1 ].width = Inches(2.0 )
table.columns[2 ].width = Inches(1.5 )
headers = ['姓名' , '部门' , '职位' ]
for i, header in enumerate (headers):
cell = table.rows[0 ].cells[i]
cell.text = header
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.bold = True
合并单元格
cell_a = table.rows[0 ].cells[0 ]
cell_b = table.rows[0 ].cells[1 ]
cell_a.merge(cell_b)
cell_a = table.rows[0 ].cells[0 ]
cell_b = table.rows[1 ].cells[0 ]
cell_a.merge(cell_b)
修订跟踪
启用修订跟踪 from docx import Document
doc = Document()
para = doc.add_paragraph()
run = para.add_run('这是新添加的文本' )
run.font.highlight_color = 7
接受/拒绝修订 使用 python-docx 库直接处理修订跟踪比较复杂,建议使用 LibreOffice 命令行:
soffice --headless --accept-all-revisions input.docx
soffice --headless --reject-all-revisions input.docx
评论
添加评论 from docx import Document
from docx.shared import Pt
doc = Document()
para = doc.add_paragraph('这是一段需要评论的文本' )
Windows 平台添加评论 import win32com.client
word = win32com.client.Dispatch("Word.Application" )
word.Visible = False
doc = word.Documents.Open("document.docx" )
selection = word.Selection
selection.Find.Execute("需要评论的文本" )
doc.Comments.Add(selection.Range, "这是评论内容" )
doc.Save()
doc.Close()
word.Quit()
页面设置
页面大小和方向 from docx import Document
from docx.shared import Inches
from docx.enum.section import WD_ORIENT
doc = Document()
section = doc.sections[0 ]
section.page_width = Inches(8.5 )
section.page_height = Inches(11 )
section.orientation = WD_ORIENT.LANDSCAPE
页边距 section = doc.sections[0 ]
section.top_margin = Inches(1 )
section.bottom_margin = Inches(1 )
section.left_margin = Inches(1.25 )
section.right_margin = Inches(1.25 )
页眉页脚
添加页眉 from docx import Document
doc = Document()
header = doc.sections[0 ].header
para = header.paragraphs[0 ]
para.text = "文档标题"
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
添加页脚和页码 from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document()
footer = doc.sections[0 ].footer
para = footer.paragraphs[0 ]
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = para.add_run()
run._element.append(parse_xml(r'<w:fldSimple xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" w:instr="PAGE"/>' ))
参考资料
相关免费在线工具 RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
随机西班牙地址生成器 随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online