Showing posts with label microsoft word. Show all posts
Showing posts with label microsoft word. Show all posts

Friday, March 30, 2018

Python docx Highlight Matching Text in Microsoft Word Doc

"""Usage : python /home/you/script/this.py file.docx 'phrase to highlight'  # notice the quotes
"""

from docx import Document
from docx.enum.text import WD_COLOR_INDEX
import sys

source = sys.argv[1]
phrase = " ".join(sys.argv[2:]).strip("'")

doc = Document( source )

for para in doc.paragraphs :
start = para.text.find( phrase )
if start > -1 :
pre = para.text[:start]
post = para.text[start+len(phrase):]
para.text = pre
para.add_run(phrase)
para.runs[1].font.highlight_color = WD_COLOR_INDEX.YELLOW
para.add_run(post)

doc.save( source )

Python docx Tutorial

Don't install docx, install python-docx

$ pip install python-docx

>>> from docx import Document

Then, a basic one is :

doc = Document.('docName.docx')
for para in doc.paragraphs :
   print para.text

How should you know that you have paragraphs and text for each para? You can use the TAB key when you've typed "doc." (without the quotes, of course).

Search and Highlight (Permanently) in Microsoft Word

You want to be productive - you have a phrase (or word) that appears multiple times in your doc, and you want to highlight all occurrences.

CTRL-h : launches the Find and Replace dialog

Click on More to get to more options to allow you to specify what format to use for the replacement.


Fill in the fields - unfortunately, Word hasn't heard of NEdit or vi and you can't even do simple things like regex and replace-with-portion-of-match, etc..


Click on Replace All and then, enjoy!!