我是python-docx的新手,发现paragraph.add_run()
总是在段落末尾添加文本。但是我需要做的是在段落中插入一个句子。具体来说:
谢谢!
答案 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."