如何用python-docx为段落应用样式?

3 投票
1 回答
11223 浏览
提问于 2025-04-18 02:08

我正在尝试使用python-docx模块给文档中的段落应用样式。我可以写新的文本,但无法给之前写的段落应用不同的样式。

这里有个例子:

x = docx.Document('Sample.docx')

x
Out[81]: <docx.api.Document at 0x121cebed0>

x.paragraphs[2].style
Out[82]: 'Normal'

x.paragraphs[2].style = 'Title'

x.paragraphs[2].style
Out[84]: 'Normal'

从文档中我无法判断这是否应该有效。文档似乎表明段落样式是可以写的,但里面没有这个用法的例子。

请告诉我这是我的问题,还是这个功能还没有实现。

1 个回答

3

这些调用是被支持的。我需要更仔细地查看一下Sample.docx文件,才能帮你解决问题。

你可以一步一步来,打印出每一步的结果,看看会得到什么?

比如:

>>> document = Document('Sample.docx')
>>> document
<docx.api.Document at 0x121cebed0>  # this looks good so far
>>> paragraphs = document.paragraphs
>>> paragraphs
???
>>> paragraph = paragraphs[2]
>>> paragraph
???
>>> paragraph.style = 'Title'
>>> paragraph.style
???

另外,正确获取样式名称有时候也挺麻烦的。我不太明白这会如何导致你遇到的情况,但值得检查一下。你确定在Sample.docx中有'标题'这个样式吗?

撰写回答