跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
PythonAI

如何编写高质量的 AI Skill:基于 skill-creator 最佳实践

综述由AI生成基于 Anthropic 官方 skill-creator 仓库,提炼出编写高质量 Agent Skill 的完整方法论。文章解析了 SKILL.md 的核心结构(YAML Frontmatter 与 Body),总结了上下文管理、自由度设置、渐进式披露等七大核心原则,并提供了从理解需求到迭代优化的六步创建流程。同时介绍了 Agent Skills 开放标准及目录规范,并通过文档处理 Skill 的完整代码示例,展示了如何在 OpenCode、Claude Code 等工具中实现专业技能集成。

苹果系统发布于 2026/4/5更新于 2026/5/2131 浏览
如何编写高质量的 AI Skill:基于 skill-creator 最佳实践

解析 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     # Skill 初始化脚本
    ├── 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 正文结构

正文使用祈使形式(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 示例:

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:避免信息重复

源码原文(Avoid duplication):

'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.py
webapp-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.'

迭代流程:

  1. 在真实任务中使用 Skill
  2. 注意困难或低效的地方
  3. 识别 SKILL.md 或资源的更新点
  4. 实现更改并再次测试

五、Agent Skills 开放标准

5.1 什么是 Agent Skills?

Agent Skills 是一个开放标准(agentskills.io),最初由 Anthropic 开发,现已被多个 AI 工具采纳:OpenCode,Claude Code,Cursor,GitHub Copilot,Ampcode,trae

5.2 标准规范要点

目录结构:

skill-name/
└── SKILL.md # 必需

可选目录:

  • scripts/ - 可执行代码
  • references/ - 参考文档
  • assets/ - 静态资源

SKILL.md 格式:

---
name: skill-name # 必需,1-64 字符
description: What this skill does # 必需,1-1024 字符
license: Apache-2.0 # 可选
compatibility: Requirements # 可选,1-500 字符
metadata:
  author: example-org
  version: "1.0"
---
# Markdown body with instructions

5.3 OpenCode 中的 Skill 存放位置

项目级 Skill:

.opencode/skills/<name>/SKILL.md # OpenCode 格式
.claude/skills/<name>/SKILL.md   # Claude 兼容格式
.agents/skills/<name>/SKILL.md   # Agents 兼容格式

全局 Skill:

~/.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              # Skill 定义文件(核心)
├── README.md             # 使用说明
├── scripts/              # 可执行脚本
│   ├── extract_text.py   # 文本提取
│   ├── add_toc.py        # 添加目录
│   └── convert_format.py # 格式转换
├── references/           # 参考文档
│   ├── ooxml-reference.md # OOXML 技术参考
│   └── 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"
---
# DOCX 处理器

## 快速参考

| 任务 | 方法 |
|-----|------|
| 提取文本 | `python scripts/extract_text.py document.docx` |
| 添加目录 | `python scripts/add_toc.py document.docx` |
| 格式转换 | `python scripts/convert_format.py input.docx output.pdf` |

## 详细指南

### 提取文档内容
使用脚本提取纯文本:
```bash
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

使用信纸模板

创建带公司信头的新文档:

from docx import Document
# 加载模板
doc = Document('assets/letterhead-template.docx')
# 添加内容
doc.add_paragraph('正文内容...')
# 保存
doc.save('output.docx')

高级功能

  • 修订跟踪:参见 references/formatting-guide.md
  • OOXML 细节:参见 references/ooxml-reference.md

### 6.3 scripts/add_toc.py

```python
#!/usr/bin/env python3
"""
为 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

#!/usr/bin/env python3
"""
转换 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:
        # 使用 soffice 进行转换
        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
        # LibreOffice 生成的文件名可能与预期不同
        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()

6.5 scripts/extract_text.py

#!/usr/bin/env python3
"""
提取 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


## 常用操作

### 解压文档
```bash
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"/> <!-- 宽度 50% -->
  </w:tblPr>
  <w:tr> <!-- 表格行 -->
    <w:tc> <!-- 表格单元格 -->
      <w:p>
        <w:r>
          <w:t>单元格内容</w:t>
        </w:r>
      </w:p>
    </w:tc>
  </w:tr>
</w:tbl>

常用命名空间

前缀命名空间说明
whttp://schemas.openxmlformats.org/wordprocessingml/2006/mainWord 主命名空间
rhttp://schemas.openxmlformats.org/officeDocument/2006/relationships关系命名空间
wphttp://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 标准文档
  • python-docx 文档
  • Office Open XML 简介

### 6.7 references/formatting-guide.md

```markdown
# 格式化指南

本文档提供 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  # 1.5 倍行距
para.paragraph_format.space_before = Pt(12)  # 段前 12 磅
para.paragraph_format.space_after = Pt(12)   # 段后 12 磅

缩进

from docx.shared import Inches

para = doc.add_paragraph('首行缩进的段落')
para.paragraph_format.first_line_indent = Inches(0.5)  # 首行缩进 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)    # 字号 12pt
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  # 浅绿色高亮表示插入
# 或使用 OOXML 直接操作(需要更复杂的处理)

接受/拒绝修订

使用 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('这是一段需要评论的文本')
# python-docx 不直接支持评论
# 需要使用 OOXML 操作或 comtypes(Windows)
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
from docx.oxml.parse_xml import parse_xml

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"/>'))

参考资料

  • python-docx 官方文档
  • Word 样式指南
  • OOXML 格式规范

### 6.8 assets/letterhead-template.docx

[公司 Logo] 公司名称


[在此处添加正文内容]


地址:XXX | 电话:XXX | 邮箱:XXX

目录

  1. 解析 skill-creator:如何编写高质量的 AI Skill
  2. 一、从 skill-creator 仓库我们能学到什么?
  3. 1.1 skill-creator 是什么?
  4. 1.2 核心文件结构分析
  5. 二、SKILL.md 的核心结构解析
  6. 2.1 YAML Frontmatter(元数据头)
  7. 2.2 Body 正文结构
  8. 三、从源码提炼的 7 大核心原则
  9. 原则 1:上下文窗口是公共资源(Concise is Key)
  10. 原则 2:设置适当的自由度(Degrees of Freedom)
  11. 原则 3:渐进式披露设计(Progressive Disclosure)
  12. 原则 4:不要在 Skill 中包含辅助文档
  13. 原则 5:编写高质量的 description
  14. 原则 6:使用祈使/不定式形式
  15. 原则 7:避免信息重复
  16. 四、Skill 创建的 6 步流程(源自源码)
  17. 步骤 1:通过具体示例理解 Skill
  18. 步骤 2:规划可复用的 Skill 内容
  19. 步骤 3:初始化 Skill
  20. 步骤 4:编辑 Skill
  21. 步骤 5:打包 Skill
  22. 步骤 6:迭代优化
  23. 五、Agent Skills 开放标准
  24. 5.1 什么是 Agent Skills?
  25. 5.2 标准规范要点
  26. Markdown body with instructions
  27. 5.3 OpenCode 中的 Skill 存放位置
  28. 六、完整示例:文档处理 Skill
  29. 6.1 目录结构
  30. 6.2 SKILL.md
  31. DOCX 处理器
  32. 快速参考
  33. 详细指南
  34. 提取文档内容
  35. 添加目录
  36. 格式转换
  37. 使用信纸模板
  38. 加载模板
  39. 添加内容
  40. 保存
  41. 高级功能
  42. 6.3 scripts/add_toc.py
  43. 6.4 scripts/convert_format.py
  44. 6.5 scripts/extract_text.py
  45. 6.6 references/ooxml-reference.md
  46. OOXML 参考指南
  47. 什么是 OOXML?
  48. 文档结构
  49. 常用操作
  50. 解压文档
  51. 重新打包
  52. document.xml 结构
  53. 段落 (Paragraph)
  54. 表格 (Table)
  55. 常用命名空间
  56. 修订跟踪
  57. 插入的文本
  58. 删除的文本
  59. 样式引用
  60. 段落样式
  61. 文本样式
  62. 页眉页脚
  63. 页眉引用
  64. 页脚引用
  65. 参考资料
  66. 6.7 references/formatting-guide.md
  67. 格式化指南
  68. 目录
  69. 样式系统
  70. 内置样式
  71. 使用样式的最佳实践
  72. 段落格式
  73. 对齐方式
  74. 其他选项:
  75. WDALIGNPARAGRAPH.LEFT # 左对齐
  76. WDALIGNPARAGRAPH.RIGHT # 右对齐
  77. WDALIGNPARAGRAPH.JUSTIFY # 两端对齐
  78. 行距和段间距
  79. 缩进
  80. 字符格式
  81. 字体设置
  82. 中文字体
  83. 列表和编号
  84. 项目符号列表
  85. 编号列表
  86. 多级列表
  87. 一级
  88. 二级
  89. 三级
  90. 表格格式
  91. 创建表格
  92. 设置列宽
  93. 填充数据
  94. 合并单元格
  95. 横向合并
  96. 纵向合并
  97. 修订跟踪
  98. 启用修订跟踪
  99. 添加修订标记的文本
  100. 插入的文本(带修订标记)
  101. 或使用 OOXML 直接操作(需要更复杂的处理)
  102. 接受/拒绝修订
  103. 接受所有修订
  104. 拒绝所有修订
  105. 评论
  106. 添加评论
  107. python-docx 不直接支持评论
  108. 需要使用 OOXML 操作或 comtypes(Windows)
  109. Windows 平台添加评论
  110. 选择文本
  111. 添加评论
  112. 页面设置
  113. 页面大小和方向
  114. 获取第一节
  115. 设置页面大小
  116. 设置横向
  117. 页边距
  118. 页眉页脚
  119. 添加页眉
  120. 获取默认页眉
  121. 添加页眉内容
  122. 添加页脚和页码
  123. 添加页码(需要域代码)
  124. 使用域代码添加页码
  125. 参考资料
  126. 6.8 assets/letterhead-template.docx
  • 💰 8折买阿里云服务器限时8折了解详情
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • Kotlin 相等性判断:结构相等与引用相等详解
  • 三种方法让老板秒懂大模型
  • C++11 线程库详解
  • LangChain4j 中 ReAct Agent 的工作原理与实现方法
  • Elasticsearch 中查询 Top10 数据的两种实现方式
  • Llama 开源家族演进:从 Llama-1 到 Llama-3 技术梳理
  • Python 量化实战:AKshare 零成本获取全市场金融数据
  • 腾讯开源 HunyuanVideo 1.5:8.3B 参数模型支持消费级显卡部署
  • 行星减速器:原理、C++ 实现与工程选型指南
  • 通义千问 3-14B 对话机器人搭建指南
  • Java 二分查找算法实战:从基础到进阶
  • 【愚公系列】《AI短视频创作一本通》012-AI 短视频分镜头设计(AI绘画提示词入门)
  • OpenClaw 16 款 AI Agent 选型指南
  • vkedit:Vue3 Web 图形编辑器 npm 包,支持标签/票据/二维码设计
  • 柔性抓取“慧眼”:MEMS 3D 视觉如何识别无序堆叠钣金件?
  • CoPaw:阿里云通义个人智能体工作台
  • Git-AI:追踪 AI 生成代码的开源扩展工具
  • 从零开始用 Python 复现 LLaMA 4 MoE 架构
  • LeetCode 202. 快乐数:快慢指针解题思路与实现
  • Spring Boot 日志框架与配置详解

相关免费在线工具

  • 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