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

时间:2019-12-15 08:30:37

标签: python python-docx

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

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

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

谢谢!

1 个答案:

答案 0 :(得分: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."