Find and Highlight Text in Word using Python

Andrew Wilson
2 min readMar 5, 2024

When searching for specific keywords or phrases within a lengthy document or report, the “Find” feature in Microsoft Word allows you to quickly locate these elements. Additionally, you can highlight the found text to make them stand out and easier to identify.

In this article, we will explore how to use Python to find and highlight specific text in Word programmatically.

Python Word Library — Installation

To find and highlight specific text in Word in Python, we will need the third-party library — Spire.Doc for Python. Before diving into the code, ensure that you have installed it on your system:

pip install Spire.Doc

Code Example:

Below is a basic code example of how to find and highlight all instances of a specified text in a Word document using Python:

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word document
document.LoadFromFile("Python.docx")

# Find all instances of a specific text
textSelections = document.FindAllString("python", False, True)

# Loop through all the instances
for selection in textSelections:
# Get the current instance as a single text range
textRange = selection.GetAsOneRange()
# Highlight the text range with a color
textRange.CharacterFormat.HighlightColor = Color.get_Yellow()

# Save the result document
document.SaveToFile("Find&HighlightAll.docx", FileFormat.Docx2016)
document.Close()

Result document:

Find All Instance of a Specified Text in Word

The above example demonstrates find and highlight all instances of a specified text in Word using Python. If you only need to find and highlight the first instance of a specified text, you can use the Document.FindString(matchString: str, caseSensitive: bool, wholeWord: bool) method provided by Spire.Doc for Python library.

Code snippet:

# Find the first instance of a specific text
textSelection = document.FindString("python", False, True)

# Get the instance as a single text range
textRange = textSelection.GetAsOneRange()

# Highlight the text range with a color
textRange.CharacterFormat.HighlightColor = Color.get_Yellow()

Output:

Find the First Instance of a Specified Text

📝 If you want to learn more about the Word document processing capabilities of this Python library, check out this documentation.

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.