Skip to main content
 首页 » 编程设计

python之提取 MS Word 文档格式元素以及原始文本信息

2025年04月02日20rubylouvre

在this post @mikemaccana 描述了如何使用 python-docx从 python 中的 MS Word 文档中提取原始文本数据。我想更进一步。除了简单地提取原始文本信息,我还可以使用此模块来获取有关字体(例如粗体与斜体)或字体大小(例如 12 与 18pt)的信息。我最接近的是this post询问有关使用此模块提取突出显示的文本条目的问题。

看起来有点抽象,我不太确定这里发生了什么。有没有更直接的方法从 python 中的 Word 文档中提取格式信息?通过快速文档模板:

Here the first line is a large header with one sentence.

The second line is slightly smaller. It also has two sentences.

Even smaller. But that's not all. This line has three sentences.

And finally here's a regular line of unbolded text.

如果我们将这四行称为我的 word 文档,我想编写一个解析函数,将其称为 doc_parser,它会返回如下内容类似: p>

>>>> doc_data = doc_parser(path_to_example_doc) 
>>>> print(doc_data) 
[1] [{'font': 18, 'face': 'bold', 'n_sentence': 1},  
{'font': 16, 'face': 'bold', 'n_sentence': 2},  
{'font': 14, 'face': 'bold', 'n_sentence': 3},  
{'font': 12, 'face': 'plain', 'n_sentence': 1}] 

请您参考如下方法:

字符级格式(“字体”)属性在运行级别可用。一个段落由运行组成。所以你可以通过下降到那个级别来获得你想要的东西,比如:

for paragraph in document.paragraphs: 
    for run in paragraph.runs: 
        font = run.font 
        is_bold = font.bold 
        etc. 

您可能遇到的最大问题是运行只知道直接应用到它的格式。如果它看起来是因为应用了样式而呈现的样子,您将必须查询样式(它也有一个字体对象)以查看它具有哪些属性。

请注意,Mike 所说的 python-docx 是在 v0.2.0(现在是 0.8.6)之后完全重写的遗留版本。文档在这里:http://python-docx.readthedocs.org/en/latest/