Python-docx: 是否可以在特定位置(不是末尾)添加新的 运行 段落

Python-docx: Is it possible to add a new run to paragraph in a specific place (not at the end)

我想在 MS Word 文本中为更正后的单词设置样式。 由于无法更改 运行 内的文本样式,我想在现有段落中插入具有新样式的新 运行...

for p in document.paragraphs: 
   for run in p.runs: 
       if 'text' in run.text:      
            new_run= Run()
            new_run.text='some new text' 
            # insert this run into paragraph
            # smth like:
            p.insert(new_run) 

怎么做?

p.add_run() 添加 运行 段落结尾,不是吗?

更新

最好能克隆运行(并插入到某个运行之后)。这样我们就可以在 new/cloned 中重现原始 运行 的样式属性。

更新 2

我可以管理那个插入代码:

if 'text' in run.text:
    new_run_element = CT_R() #._new() 
    run._element.addnext(new_run_element)
    new_run = Run(new_run_element, run._parent)
    ...

但在那之后:

  1. 段落运行的编号保持不变len(p.runs)
  2. 当我将该文档保存在文件中时,MS Word 无法打开它

没有 API 支持,但可以在 oxml/lxml 级别轻松完成:

from docx.text.run import Run
from docx.oxml.text.run import CT_R
# ...
for run in p.runs:
    if 'text' in run.text:
        new_run_element = p._element._new_r()
        run._element.addnext(new_run_element)
        new_run = Run(new_run_element, run._parent)
        # ---do things with new_run, e.g.---
        new_run.text = 'Foobar'
        new_run.bold = True

如果要在现有 运行 之前插入新的 运行,请使用 run._element.addprevious(new_run_element)。这两个是 lxml.etree._Element class 上的方法,其中所有 python-docx 元素 subclass.
https://lxml.de/api/lxml.etree._Element-class.html