Word headings: don't just look at font size, styles are the better structural cue

The article resolves the core paragraph.style and localized-name issues in the brief, offering clear boundaries, an in-memory example, an acceptance checklist, and OmniDoc integration tips. It is clear, error-free, and backed by official vendor documentation.

Key points of this article

  • Heading recognition should be based on paragraph styles, not on visual formatting such as font size and bold.
  • Built-in styles are always named in English in the XML, such as Heading 1; looking up "标题 1" will raise a KeyError.
  • Custom style names must match the interface display and not be localized; a name mapping table needs to be established.
  • Paragraphs whose style is Normal but whose font size and bold formatting make them stand out should be flagged as suspected headings pending manual confirmation.
  • When a paragraph with missing styling is encountered, a warning should be logged and the paragraph should be handled as plain text, so that the entire parsing process does not crash.

If you use a script to batch-extract the table of contents or sections from Word documents, you may find that a "level-one heading" is missed, or that a bold paragraph of body text is misidentified as a section. This is usually not because the regular expression is poorly written, but because the paragraph has not been assigned a heading style such as Heading 1; the text has simply been manually enlarged and bolded. In Word document structure processing, visual appearance does not equal structure, and paragraph.style is the more reliable semantic clue.

The content below is suited to developers and documentation engineers responsible for document automation, batch parsing, or pre-translation checks. The examples use synthetic samples generated in memory, making them easy to reproduce and understand. Before processing important files, keep the originals, and review them against the boundaries and acceptance items described in the text.

How does Word recognize headings? One-sentence conclusion

One-sentence conclusion: Use paragraph.style as the primary basis for judging headings, and look up styles via the English internal names or the mapping table, rather than relying only on font size and bold formatting.

Your situationRecommended PracticesCause
Extract the chapter structure from WordRecognize headings according to paragraph.styleVisual appearance is not the same as structure; styling is the reliable semantic cue.
In the code, I need to look up built-in styles, and the document may be the Chinese version.Use the internal English names such as Heading 1, or create a localized name mapping table.Built-in styles are stored in English in the XML, and using styles['标题 1'] throws KeyError.
The document uses custom stylesLook up directly by style nameCustom style names are kept consistent with the interface display in the XML and are not subject to localization conversion.
The paragraph quote style has been removedFirst check whether the style object exists, and fall back to plain text when it cannot be recognizedDirect access to paragraph.style.name may return None or throw an exception
The paragraph has only large font size and bold formatting; the style is NormalMarked as "suspected heading," pending manual confirmationVisually prominent but semantically unstyled content should not be automatically promoted to a structural node.

Why You Must Use the English Internal Name to Look Up Styles

python-docx operates on the underlying WordprocessingML files, not on the Word application interface. Regardless of whether the user's Word is in Chinese, Japanese, or German, the storage names of built-in styles are in English. For example, "Heading 1" displayed in the Chinese Word interface is recorded in XML as Heading 1. For how styles are stored and named, refer to Understanding Styles - python-docx Concept Overview.

If the code uses styles['标题 1'] for lookup, the program will throw KeyError directly. This is one of the common pitfalls when handling multilingual documents.

Custom styles are not subject to this restriction; their names in the XML match exactly what users see in the interface. Therefore, when writing robust parsing logic, you can either build a mapping table from localized display names to English internal names, or require document submitters to use a standard template.

Synthetic example: correct output and edge cases

To demonstrate the logic of style recognition, we construct a synthetic sample containing three typical types of paragraphs:

  1. Paragraph A: The Heading 1 style is applied, and the text reads "第一章 引言".
  2. Paragraph B: The style is Normal, but a manual font size of 16pt and bold have been set; the text reads "重要提示".
  3. Paragraph C: The custom style MyCustomTitle is applied, and the text reads "附录说明".

Expected output: The parser should return a structured list in which only paragraphs A and C are marked as heading nodes. Paragraph B, although visually prominent, lacks semantic styling and should be classified as ordinary body text, or flagged as "suspected heading pending manual confirmation"; it must not be automatically promoted to a structural node.

Error and boundary inputs: If a paragraph in the document references a style that has been deleted, i.e., w:pStyle w:val="DeletedStyle" exists in the XML but the style definition is missing, then python-docx accessing paragraph.style.name may return None or throw an exception. A safer approach is to check whether the style object exists before accessing it, or to downgrade such paragraphs to plain text, so that the entire parsing process is not interrupted.

In-memory sample building and style assertion code

The code below shows how to verify style-recognition logic in a controlled environment. It is meant to demonstrate API usage and assertion strategy, and is not a production-grade parser. In actual use, run it in an environment where you have locked the dependency versions; python-docx>=0.8.11 is recommended. For the specific usage of the style, refer to Working with Styles - python-docx official documentation.

from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Pt

def build_sample_doc():
    """构建含混合样式的合成文档,无需外部文件"""
    doc = Document()
    # 标准内置标题
    doc.add_heading('Chapter One', level=1)
    # 视觉像标题但无样式
    p_visual = doc.add_paragraph('Visual Fake Title')
    run = p_visual.runs[0]
    run.bold = True
    run.font.size = Pt(15)  # 使用Pt单位确保API规范
    # 自定义样式
    if 'MyCustomTitle' not in [s.name for s in doc.styles]:
        doc.styles.add_style('MyCustomTitle', WD_STYLE_TYPE.PARAGRAPH)
    doc.add_paragraph('Appendix Note', style='MyCustomTitle')
    return doc

def extract_semantic_headings(doc):
    """仅提取具有明确样式的标题,忽略直接格式化"""
    headings = []
    for para in doc.paragraphs:
        style_name = para.style.name if para.style else None
        # 严格匹配:内置Heading或已知自定义标题样式
        if style_name and (style_name.startswith('Heading ') or style_name == 'MyCustomTitle'):
            headings.append({'text': para.text, 'style': style_name})
    return headings

# 验证逻辑
sample = build_sample_doc()
result = extract_semantic_headings(sample)

assert len(result) == 2, f"期望2个语义标题,实际得到{len(result)}个"
assert result[0]['style'] == 'Heading 1'
assert result[1]['style'] == 'MyCustomTitle'
assert all('Visual Fake' not in item['text'] for item in result)

This code explicitly excludes the approach of identifying headings based only on font properties. assert is used to confirm that the logic behaves as expected. However, in real documents, you can replace the assertions with logging or an exception-collection mechanism, so that issues can be reviewed uniformly during batch processing.

Acceptance Checklist and Boundaries for Manual Review

Automated parsing cannot cover every formatting convention. The table below summarizes how common scenarios are handled, helping the team define the boundary of collaboration between machines and humans.

Observe the phenomenonHandling decisionDoes it require manual review?
Paragraph style is Heading XExtract directly as structural nodesNo
The style is Normal, but the font size is ≥14pt and bold.Marked as "suspected heading", original position information retainedYes
Style names containing "标题" but not built-in (such as "章节标题")Check the mapping table; if there is no corresponding entry, treat it as body text.Depending on the integrity of the view mapping
paragraph.style as NoneRecord the warning and handle it as plain text.(When appearing in bulk)
Custom style inherits from Heading 1Traceable via the base_style chain, considered a valid title.No (if the inheritance chain is complete)

Note that this table is for logic validation at the code-demonstration level. End-to-end results still need to be assessed against the specific document type. For example, "definitions" clauses in legal contracts may use specialized styles and should not be treated as section headings. In technical manuals, "precautions" may need special handling during translation even when they use Heading 3. When such domain-specific rules come up, a manual review step should be added.

📊 Core Comparison

Basis for judgmentCan it serve as a structural node?Explanation
Paragraph style is Heading XCan it be extracted directly?The style itself carries meaning, so no manual confirmation is needed.
The style is Normal, with only large font size and bold.Not automatically promotedMarked as suspected heading, awaiting manual confirmation
Custom style inherits from Heading 1A heading is considered valid when its inheritance chain is complete.Traceable via the base_style chain

🎯 Which Approach Suits You?

If you need to extract the table of contents or section structure from Word

Prioritize using paragraph.style for determination; do not rely on font size and bold formatting.

If you need to handle localized versions of Word documents, such as Chinese or Japanese

Look up built-in styles by their English internal names, or build a mapping table from localized names to internal names.

If your document was written by multiple people and the formatting is inconsistent

For paragraphs styled Normal but visually prominent, keep a manual review step and record their location information.

If you are handling legal contracts or technical manuals

First, map out the domain-specific style conventions, then decide which passages can be identified automatically and which require human judgment.

❓ Frequently Asked Questions (FAQ)

1. Why can't styles['标题 1'] be used directly to find headings?

Because python-docx reads the underlying XML, where built-in styles are stored under English names, such as Heading 1. Using the name "标题 1" (Heading 1) shown in the Chinese Word interface in code will cause KeyError.

2. Can a paragraph with only a large font size and bold formatting be treated as a heading?

It is not advisable to treat it as a heading automatically. Such paragraphs lack semantic styling and should be marked as "suspected headings," with a decision on whether to include them in the document structure made after manual confirmation.

3. How should I handle a paragraph whose style is None?

It is recommended to log a warning and treat the paragraph as plain text. If this situation occurs frequently across a batch of files, arrange for manual review.

4. Can a custom style be used as a heading?

If a custom style inherits from Heading 1 and the base_style inheritance chain is complete, it can be treated as a valid heading.

📝 Summary

When judging Word headings, rely primarily on the paragraph styles rather than only on visual appearance. Even after the code validation passes, you still need to combine it with the specific document type and manual review to confirm that the results are reliable.

Try it now: upload a document and start translating right away, with the original layout preserved.

Updated 2026-11-29