mcpField
D
docx-advanced-patterns

docx-advanced-patterns

github.com/belumume文档处理4637 次安装6 周前更新
代码仓库

关于 docx-advanced-patterns

docx-advanced-patterns 是一项使用 python-docx 处理复杂 DOCX 结构的技能,重点提取嵌套表格及基础文本提取遗漏的单元格内容,并补充官方 docx 技能。

主要功能

  1. 01提取嵌套表格文本
  2. 02递归处理多层嵌套表格
  3. 03检测含嵌套表格的单元格
  4. 04处理复选框与表单内容
  5. 05保留换行和内容结构

适用场景

  1. 01提取政府表单中的复选项
  2. 02读取评估表中的评分选项
  3. 03处理复杂表格单元格数据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/belumume/claude-skills --skill docx-advanced-patterns

安装后在 Claude Code 中输入/docx-advanced-patterns确认已加载。

附带文件README.md

详细介绍

DOCX 高级模式技能

用于处理基本 .text 提取无法覆盖的复杂文档结构的 python-docx 专用模式。

何时使用此技能

处理具有以下特征的 DOCX 文件时,请调用此技能:

  • 表格单元格中嵌套表格
  • 带复选框选项的表单
  • 复杂的多行单元格布局
  • 嵌入选项的清单
  • 使用 .text 属性无法显示内容的单元格

请与官方 docx 技能一同使用,以全面处理文档。

核心模式:嵌套表格提取

问题

python-docx 的 cell.text 属性只会提取直接段落文本,不会遍历单元格中的嵌套表格。

症状:

cell.text  # Returns: '' or '\n'
# But cell visually contains content!
检测

检查单元格是否包含嵌套表格:

if cell.tables:
    print(f"Found {len(cell.tables)} nested table(s)")
    # Cell has nested content - need special extraction
解决方案(简单)
def extract_cell_content_with_nested_tables(cell):
    """
    Extract all text from a cell, including text from nested tables.

    Args:
        cell: python-docx _Cell object

    Returns:
        str: Combined text from cell paragraphs and nested tables
    """
    text_parts = []

    # Get direct paragraph text (not inside nested tables)
    for para in cell.paragraphs:
        para_text = para.text.strip()
        if para_text:
            text_parts.append(para_text)

    # Get content from nested tables
    if cell.tables:
        for nested_table in cell.tables:
            for nested_row in nested_table.rows:
                # For checkbox lists: Column 0 = label, Column 1 = checkbox
                # Extract text from first column only
                if nested_row.cells:
                    first_col_text = nested_row.cells[0].text.strip()
                    # Filter out checkbox characters
                    if first_col_text and first_col_text not in ['', '☐', '☑', '☒']:
                        text_parts.append(first_col_text)

    return '\n'.join(text_parts) if text_parts else ''
解决方案(递归处理深层嵌套)

适用于包含多层表格嵌套的文档:

def extract_cell_content_recursively(cell):
    """
    Recursively extract text from cell including deeply nested tables.

    Handles arbitrary nesting depth.
    """
    text_parts = []

    def _extract_recursive(cell_obj):
        # Get direct paragraphs
        for para in cell_obj.paragraphs:
            para_text = para.text.strip()
            if para_text and para_text not in ['', '☐', '☑', '☒']:
                text_parts.append(para_text)

        # Recursively get nested tables
        for nested_table in cell_obj.tables:
            for nested_row in nested_table.rows:
                for nested_cell in nested_row.cells:
                    _extract_recursive(nested_cell)

    _extract_recursive(cell)
    return '\n'.join(text_parts) if text_parts else ''

使用示例

示例 1:提取表单复选框选项

文档结构:

Table Cell contains:
  Nested Table:
    Row 1: "High potential" | ☐
    Row 2: "Moderate potential" | ☐
    Row 3: "Low potential" | ☐

提取:

from docx import Document

doc = Document('form.docx')
table = doc.tables[0]
cell = table.rows[1].cells[0]

# Wrong way - returns empty
basic_text = cell.text
print(basic_text)  # Output: '' or '\n'

# Right way - extracts nested content
full_text = extract_cell_content_with_nested_tables(cell)
print(full_text)
# Output:
# High potential
# Moderate potential
# Low potential
示例 2:处理表格中的所有单元格
def process_table_with_nested_content(table):
    """Process all cells, handling nested tables"""
    for row in table.rows:
        for cell in row.cells:
            # Extract with nested table support
            content = extract_cell_content_with_nested_tables(cell)

            if content:
                # Process content (translate, analyze, etc.)
                processed = do_something_with(content)
                print(f"Cell content: {processed}")
示例 3:检测嵌套表格
def analyze_document_structure(doc):
    """Find all cells with nested tables"""
    nested_cells = []

    for t_idx, table in enumerate(doc.tables):
        for r_idx, row in enumerate(table.rows):
            for c_idx, cell in enumerate(row.cells):
                if cell.tables:
                    nested_cells.append({
                        'table': t_idx,
                        'row': r_idx,
                        'col': c_idx,
                        'nested_count': len(cell.tables)
                    })

    return nested_cells

# Usage
doc = Document('complex_form.docx')
nested = analyze_document_structure(doc)

for item in nested:
    print(f"Table {item['table']}, Row {item['row']}, Col {item['col']}: "
          f"{item['nested_count']} nested table(s)")

常见用例

1. 政府表单

表单通常使用嵌套表格来排列复选框:

def extract_form_responses(doc):
    """Extract all form checkbox options"""
    responses = {}

    for table in doc.tables:
        for row in table.rows:
            # First cell = question
            question = row.cells[0].text.strip()

            # Second cell = checkbox options (nested table)
            if row.cells[1].tables:
                options = extract_cell_content_with_nested_tables(row.cells[1])
                responses[question] = options.split('\n')

    return responses
2. 评估表单

提取评分量表和选项:

def extract_evaluation_items(doc):
    """Extract evaluation criteria and options"""
    evaluations = []

    for table in doc.tables:
        for row_idx, row in enumerate(table.rows[1:], 1):
            # Get criterion
            criterion = row.cells[0].text.strip()

            # Get rating options (often nested)
            rating_cell = row.cells[1]
            rating_options = extract_cell_content_with_nested_tables(rating_cell)

            evaluations.append({
                'criterion': criterion,
                'options': rating_options.split('\n')
            })

    return evaluations
3. 复杂数据表

从包含嵌套布局的单元格中提取结构化数据:

def extract_complex_cell_data(cell):
    """Extract data from cells with complex nested structures"""
    data = {
        'main_content': '',
        'nested_items': []
    }

    # Direct paragraphs
    for para in cell.paragraphs:
        if para.text.strip():
            data['main_content'] = para.text.strip()
            break

    # Nested table data
    if cell.tables:
        for nested_table in cell.tables:
            for nested_row in nested_table.rows:
                row_data = [c.text.strip() for c in nested_row.cells]
                data['nested_items'].append(row_data)

    return data

与官方 docx 技能集成

此技能是官方 docx 技能的补充:

官方 docx 技能提供:

  • 文档创建(docx-js)
  • 基本文本提取(pandoc)
  • 修订工作流
  • 评论处理
  • 复杂情况下的 XML 访问

此技能提供:

  • 嵌套表格提取
  • 复杂单元格内容处理
  • 表单和清单处理
  • 高级内容提取模式

搭配使用:

# For basic operations: use official skill
from docx import Document

# For nested table handling: use this skill
from docx_advanced import extract_cell_content_with_nested_tables

# Combine both
doc = Document('complex_form.docx')  # Official
for table in doc.tables:            # Official
    for row in table.rows:          # Official
        for cell in row.cells:      # Official
            # Advanced extraction:
            content = extract_cell_content_with_nested_tables(cell)

性能注意事项

对于大型文档:

缓存嵌套表格检查结果:

def build_nested_table_cache(doc):
    """Pre-compute which cells have nested tables"""
    cache = {}

    for t_idx, table in enumerate(doc.tables):
        for r_idx, row in enumerate(table.rows):
            for c_idx, cell in enumerate(row.cells):
                if cell.tables:
                    cache[(t_idx, r_idx, c_idx)] = len(cell.tables)

    return cache

# Usage
cache = build_nested_table_cache(doc)

for t_idx, table in enumerate(doc.tables):
    for r_idx, row in enumerate(table.rows):
        for c_idx, cell in enumerate(row.cells):
            if (t_idx, r_idx, c_idx) in cache:
                # This cell has nested tables
                content = extract_cell_content_with_nested_tables(cell)
            else:
                # Regular extraction
                content = cell.text

故障排除

问题:尽管内容可见,提取结果仍为空

诊断:

cell = table.rows[1].cells[0]
print(f"cell.text: '{cell.text}'")
print(f"cell.tables: {len(cell.tables)}")

if not cell.text.strip() and cell.tables:
    print("Content is in nested tables!")

修复: 使用 extract_cell_content_with_nested_tables(cell)

问题:输出中出现复选框字符(、☐)

修复: 将其过滤掉:

text = cell.text.strip()
# Remove checkbox unicode characters
clean_text = text.replace('', '').replace('☐', '').replace('☑', '').replace('☒', '')
问题:未保留多行内容

修复: 使用换行符拼接:

'\n'.join(text_parts)  # Preserves line structure

最佳实践

  1. 始终先检查是否存在嵌套表格:

    if cell.tables:
        content = extract_cell_content_with_nested_tables(cell)
    else:
        content = cell.text
    
  2. 处理复选框字符:

    CHECKBOX_CHARS = ['', '☐', '☑', '☒']
    if text not in CHECKBOX_CHARS:
        # Process text
    
  3. 保留结构:

    # Use newlines to maintain line breaks
    '\n'.join(lines)
    
  4. 使用示例文档进行测试:

    def test_extraction():
        doc = Document('sample_form.docx')
        cell = doc.tables[0].rows[1].cells[0]
    
        extracted = extract_cell_content_with_nested_tables(cell)
        assert 'High potential' in extracted
        assert 'Moderate potential' in extracted
    

参考实现

上述模式均可独立使用;此技能不附带单独的 REFERENCE.md(先前的指引已过时)。可运行示例、集成模式、递归提取和性能说明均已内嵌在上述章节中。

为 Anthropic Skills 做出贡献

此模式目前尚未纳入官方 docx 技能。如果你觉得它有用,可以考虑贡献:

  1. Fork https://github.com/anthropics/skills
  2. 添加到 document-skills/docx/SKILL.md
  3. 提交 pull request,并附上:
    • 模式说明
    • 代码示例
    • 用例

成功标准

符合以下条件即表示模式运行正常:

  • 包含嵌套表格的单元格会返回完整内容
  • 复选框选项能够正确提取
  • 表单字段清晰可读
  • 提取过程中没有内容丢失
  • 结构得到保留(换行符得到保留)

评论

支持 Markdown