如何 "insert run" 而不是 "add run" 到段落结尾

how to "insert run" instead of "add run" to the end of a paragraph

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

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

我想让它看起来像这样:

谢谢!

Paragraph 上没有 .insert_run() 方法,如果您考虑一下,它可能无论如何都不足以完成这项工作,因为不能保证每个句子都以 运行边界。如果需要的话,你需要自己做句子分析。

一个天真的第一个实现可能是这样的:

>>> 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."