DEV Community

Allen Yang
Allen Yang

Posted on

Finding and Replacing Text in Word Documents Using Python

Finding and replacing text is one of the most fundamental and frequent operations in Word document automation. Whether batch-modifying clause numbers in contracts, updating date information in reports, or standardizing terminology across multiple documents, efficient text find-and-replace capability is a core component of any document processing workflow. This article covers how to find and replace text in Word documents using Python, including plain text replacement, regex-based pattern matching, find-and-highlight, and replacing text with images.

Why Implement Find and Replace Programmatically

While Word's built-in find-and-replace feature is convenient for manual use, programmatic approaches offer irreplaceable advantages in the following scenarios:

  • Batch processing: Apply the same replacement across dozens of documents in a single operation
  • Complex matching: Use regular expressions to match text with specific patterns such as IDs, dates, or email addresses
  • Precise control: Apply fine-grained replacement strategies with case sensitivity and whole-word matching
  • Workflow integration: Embed replacement operations into larger document processing pipelines such as contract template generation or automated report creation

Environment Setup

Before starting, install the Python library that supports Word document operations.

pip install Spire.Doc
Enter fullscreen mode Exit fullscreen mode

Once installed, import the relevant modules in your script to begin working.

Basic Text Replacement

The most basic replacement operation substitutes specified text in a document with new content. The Replace() method accepts four parameters: the text to find, the replacement text, whether to ignore case, and whether to match whole words only.

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

inputFile = "Sample.docx"
outputFile = "ReplaceText.docx"

# Create a document object
document = Document()

# Load the Word file from disk
document.LoadFromFile(inputFile)

# Replace "word" with "ReplacedText" in the document
# Parameters: find text, replace text, ignore case, match whole word
document.Replace("word", "ReplacedText", False, True)

# Save the document
document.SaveToFile(outputFile, FileFormat.Docx)
document.Close()
Enter fullscreen mode Exit fullscreen mode

The second and third boolean parameters of Replace() determine the strictness of matching. False means case-sensitive matching, and True as the fourth parameter means only complete words are matched rather than partial word segments. This design allows replacement operations to precisely control the matching scope and avoid unintended substitutions.

Using Regular Expressions for Replacement

When the text to match follows a pattern rather than a fixed string, regular expressions become essential. For example, replacing all identifiers starting with #, matching dates in a specific format, or finding reference numbers.

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

inputFile = "Sample.docx"
outputFile = "ReplaceByRegex.docx"

# Create a document object
document = Document()

# Load the Word file from disk
document.LoadFromFile(inputFile)

# Create a regex pattern to match words starting with #
regex = re.compile(r"#\w+\b")

# Replace all text matching the regex pattern
document.Replace(regex, "Spire.Doc")

# Save the document
document.SaveToFile(outputFile, FileFormat.Docx)
document.Close()
Enter fullscreen mode Exit fullscreen mode

Here, Python's standard re library compile() method creates a regex object, which is then passed to document.Replace(). All text matching the pattern is uniformly replaced with the target string. This approach is particularly suitable for processing text content with regular patterns, such as:

  • Replacing all tag identifiers like #TAG001
  • Redacting all email addresses to [REDACTED]
  • Standardizing date formats, such as converting YYYY/MM/DD to YYYY-MM-DD

Finding Text and Applying Highlight

Sometimes you don't need to replace text content but rather locate all matching instances and apply visual markers. This is highly useful in document review and keyword search result marking scenarios.

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

inputFile = "Sample.docx"
outputFile = "FindAndHighlight.docx"

# Create a document object
document = Document()

# Load the Word file from disk
document.LoadFromFile(inputFile)

# Find all matching text instances
textSelections = document.FindAllString("word", False, True)

# Iterate through matches and set highlight color
for selection in textSelections:
    selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.get_Yellow()

# Save the document
document.SaveToFile(outputFile, FileFormat.Docx)
document.Close()
Enter fullscreen mode Exit fullscreen mode

The FindAllString() method returns a collection of text selections, each representing a match position in the document. Use GetAsOneRange() to obtain the corresponding text range, then access the CharacterFormat.HighlightColor property to set the highlight color. The parameter False means case-sensitive matching, and True means whole-word matching.

Replacing Text with Images

Beyond text replacement, you can also replace found text with images. This is practical in scenarios like batch-inserting logos, signatures, or product images.

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

inputFile = "Sample.docx"
outputFile = "ReplaceWithImage.docx"

# Create a document object
document = Document()

# Load the Word file from disk
document.LoadFromFile(inputFile)

# Create an image object
image = DocPicture(document)
image.LoadImage("logo.png")

# Find all "[LOGO]" placeholders
textSelections = document.FindAllString("[LOGO]", False, False)

# Replace each match with the image
for selection in textSelections:
    range = selection.GetAsOneRange()
    # Clear the original text
    range.Text = ""
    # Insert the image at the original text position
    range.ChildObjects.Add(image.Clone())

# Save the document
document.SaveToFile(outputFile, FileFormat.Docx)
document.Close()
Enter fullscreen mode Exit fullscreen mode

This approach is commonly used in template document processing: place placeholders (such as [LOGO] or [SIGNATURE]) in the document, then batch-replace them with actual images through code.

Batch Processing Multiple Documents

In real-world work, you often need to perform the same find-and-replace operation across multiple Word files in a directory. Combined with Python's file traversal capabilities, efficient batch processing becomes straightforward.

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

input_dir = "./documents"
output_dir = "./processed"

os.makedirs(output_dir, exist_ok=True)

# Iterate through all .docx files in the directory
for filename in os.listdir(input_dir):
    if filename.endswith(".docx"):
        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, filename)

        document = Document()
        document.LoadFromFile(input_path)

        # Perform replacement
        document.Replace("Old Company Name", "New Company Name", False, True)

        document.SaveToFile(output_path, FileFormat.Docx)
        document.Close()

        print(f"Processed: {filename}")
Enter fullscreen mode Exit fullscreen mode

This code iterates through all .docx files in a specified directory, performs the same text replacement on each document, and saves the results to an output directory. This pattern is highly practical in scenarios such as company renaming, terminology standardization, and template updates.

Practical Tips

Using Context-Aware Replacement

For replacement scenarios requiring more complex logic, you can check the context of each match before deciding whether to perform the replacement:

# Find all matching instances
textSelections = document.FindAllString("Python", False, True)

# Decide whether to replace based on context
for selection in textSelections:
    range = selection.GetAsOneRange()
    # Only replace when the paragraph style is a heading
    if range.OwnerParagraph.StyleName.startswith("Heading"):
        range.Text = "Python Programming"
Enter fullscreen mode Exit fullscreen mode

Preserving Formatting After Replacement

When replacing text, the original character formatting (font, color, size, etc.) is preserved by default. If you need to modify formatting simultaneously, reapply it after replacement:

textSelections = document.FindAllString("old term", False, True)
for selection in textSelections:
    range = selection.GetAsOneRange()
    range.Text = "new term"
    range.CharacterFormat.Bold = True
    range.CharacterFormat.TextColor = Color.get_Blue()
Enter fullscreen mode Exit fullscreen mode

Conclusion

This article covered multiple approaches to finding and replacing text in Word documents using Python, including basic text replacement, regex-based pattern replacement, find-and-highlight, image replacement, and batch file processing. These operations address the main scenarios from simple text modifications to complex pattern matching.

The core API revolves around two methods: Replace() for direct replacement supporting both plain strings and regular expressions, and FindAllString() for locating match positions that can be combined with formatting settings for highlight marking and other effects. With these fundamentals in place, you can combine them with Python's file handling capabilities to build efficient document batch processing workflows.

Top comments (0)