通过 text 属性,Run 可以进一步设置样式。每个属性都可以被设置为 3 个值之
一:True(该属性总是启用,不论其他样式是否应用于该 Run)、False(该属性总是禁用)或None(默认使用该Run 被设置的任何属性)。
表 13-1 列出了可以在Run 对象上设置的 text 属性。
例如,为了改变 demo.docx 的样式,在交互式环境中输入以下代码:
>>> doc = docx.Document('demo.docx')
>>> doc.paragraphs[0].text
'Document Title'
>>> doc.paragraphs[0].style
'Title'
>>> doc.paragraphs[0].style = 'Normal'
>>> doc.paragraphs[1].text
'A plain paragraph with some bold and some italic'
>>> (doc.paragraphs[1].runs[0].text, doc.paragraphs[1].runs[1].text, doc.
paragraphs[1].runs[2].text, doc.paragraphs[1].runs[3].text)
('A plain paragraph with some ', 'bold', ' and some ', 'italic')
>>> doc.paragraphs[1].runs[0].style = 'QuoteChar'
>>> doc.paragraphs[1].runs[1].underline = True
>>> doc.paragraphs[1].runs[3].underline = True
>>> doc.save('restyled.docx')
这里,我们使用了 text 和style 属性,以便容易地看到文档的段落中有什么。我们可以看到,很容易将段落划分成 Run,并单独访问每个
Run。所以我们取得了第二段中的第一、第二和第四个Run,设置每个Run 的样式,将结果保存到一个新文档。
文件顶部的单词 Document Title 将具有Normal 样式,而不是Title 样式。针对文本A plain paragraph 的Run 对象,将具有 QuoteChar
样式。针对单词 bold 和 italic的两个Run 对象,它们的underline 属性设置为True。图 13-7 展示了文件中段落和 Run 的样式看起来的样子。
访问 https://python-docx.readthedocs.org/en/latest/user/styles.html,你可以看到, python-docx 使用样式的更完整文档。