如何“插入运行”而不是“添加运行”到段落末尾

问题描述 投票:0回答:1

我是python-docx的新手,发现paragraph.add_run()总是将文本添加到段落的末尾。但是我需要做的是在段落中插入一个句子。具体来说:

我有一个如下所示的doc文件:input

并且我想使它看起来像这样:enter image description here

谢谢!

python python-docx
1个回答
1
投票

.insert_run()上没有Paragraph方法,如果您考虑一下,无论如何这可能是不够的,因为不能保证每个句子都在运行边界处结束。如果需要,您需要自己进行句子解析。

幼稚的第一个实现可能看起来像这样:

>>> paragraph = document.paragraphs[2]
>>> paragraph.text
"This is the first sentence. This is the second sentence."
>>> sentences = paragraph.text.split(". ")
>>> sentences
["This is the first sentence", "This is the second sentence."]
>>> sentences.insert(1, "And I insert a sentence here")
>>> paragraph.text = ". ".join(sentences)
>>> paragraph.text
"This is the first sentence. And I insert a sentence here. This is the second sentence."
© www.soinside.com 2019 - 2024. All rights reserved.