title: Python docx - Modify runs to target specific words
body: <p>I’m developing a code in python that searches a docx file for certain variables, for example find the word “car” and highlight it with a defined colour.</p>
  <p>I’m using the docx module to identify and highlight the text and I can apply the changes on a run level (run.font.highlight) but since MS Word stores the text in a xml file that keeps tracks of all the changes, the words I’m looking for can be split through different runs or be part of a long sentence.
  Since my final goal is to target one or multiple defined words, I’m struggling to get to this <a href="https://i.stack.imgur.com/9Oncr.png" rel="nofollow noreferrer">expected result</a>.</p>
  <p>My main idea would be to run a function to “clean” the runs or the xml file, to have my target words in isolated runs that can then be highlighted, but I haven’t found any documentation about this and I’m worried about losing fonts properties, styles, etc...</p>
  <p>This is the code that I have so far:</p>
  <pre><code>import docx
  from docx.enum.text import WD_COLOR_INDEX
  import re
  
  doc = docx.Document('demo.docx')
  
  words = {'car': 'RED',
           'bus': 'GREEN',
           'train station': 'BLUE'}
  
  for word, color in words.items():
      w = re.compile(fr'\b{word}\b')
      
      for par in doc.paragraphs:
          for run in par.runs:
              s = re.findall(w, run.text)
              if s:
                  run.font.highlight_color = getattr(WD_COLOR_INDEX, color)
  
  doc.save('new.docx')
  </code></pre>
  <p>Does anyone ever encountered the same problem or have an idea on a different approach?</p>
  <p>Thanks</p>