我想为 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()
将 run 添加到段落末尾,不是吗?
Update
最好的是能够克隆运行(并在特定运行后插入它)。通过这种方式,我们可以在新的/克隆的运行中重现原始运行的样式属性。
Update 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)
...
但在那之后:
- the 段落编号保持不变:
len(p.runs)
- as I save that doc in file, the MS Word fails to open it:
对此没有 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
类所有python-docx
元素子类。
https://lxml.de/api/lxml.etree._Element-class.html https://lxml.de/api/lxml.etree._Element-class.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)