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

2024/9/20 14:39:45

I want to set a style to a corrected word in MS Word text. Since it's not possible to change text style inside a run, I want to insert a new run with new style into the existing paragraph...

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) 

How to do it?

p.add_run() adds run to the end of paragraph, doesn't it?

Update

The best would be to be able to clone run (and insert it after a certain run). This way we reproduce the original run's style attributes in the new/cloned one.

Update 2

I could manage that insertion code:

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

But after that:

  1. the paragraph runs number is left the same: len(p.runs)
  2. as I save that doc in file, the MS Word fails to open it: enter image description here
Answer

There's no API support for this, but it can be readily accomplished at the oxml/lxml level:

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

If you want to insert the new run prior to the existing run, use run._element.addprevious(new_run_element). These two are methods on the lxml.etree._Element class which all python-docx elements subclass.
https://lxml.de/api/lxml.etree._Element-class.html

https://en.xdnf.cn/q/72160.html

Related Q&A

Chained QSortFilterProxyModels

Lets say I have a list variable datalist storing 10,000 string entities. The QTableView needs to display only some of these entities. Thats is why QTableView was assigned QSortFilterProxyModel that doe…

Python subprocess.popen() without waiting

Im using Python 3.4.2 on Windows. In script1.py Im doing this:myProc = subprocess.Popen([sys.executable, "script2.py", "argument"]) myProc.communicate()it works and call script2.py …

Python27.dll File Missing - Exception

I have downloaded my code from bit-bucket which was made by my group member. It contain all the frameworks and python script folder. But when I run this code on my system it generates the following err…

Download an Image Using Selenium Webdriver in Python

I am trying to download an image from a URL using Selenium Webdriver in Python. The site is protected by a login page, so cant just save the URL contents using requests. I am able to get text from the …

Can I turn off implicit Python unicode conversions to find my mixed-strings bugs?

When profiling our code I was surprised to find millions of calls toC:\Python26\lib\encodings\utf_8.py:15(decode)I started debugging and found that across our code base there are many small bugs, usual…

jupyter: how to stop execution on errors?

The common way to defensively abort execution in python is to simply do something like: if something_went_wrong:print("Error message: goodbye cruel world")exit(1)However, this is not good pra…

Python 2.7 on Google App Engine, cannot use lxml.etree

Ive been trying to use html5lib with lxml on python 2.7 in google app engine. But when I run the following code, it gives me an error saying "NameError: global name etree is not defined". Is …

Pandas split name column into first and last name if contains one space

Lets say I have a pandas DataFrame containing names like so:name_df = pd.DataFrame({name:[Jack Fine,Kim Q. Danger,Jane Smith, Juan de la Cruz]})name 0 Jack Fine 1 Kim Q. Danger 2 Jane Smith 3 J…

Docker. No such file or directory

I have some files which I want to move them to a docker container. But at the end docker cant find a file..The folder with the files on local machine are at /home/katalonne/flask4File Structure if it m…

How to recover original values after a model predict in keras?

This is a more conceptual question, but I have to confess I have been dealing with it for a while. Suppose you want to train a neural network (NN), using for instance keras. As it is recommended you pe…