Find and Replace Text in Word DOC or DOCX Documents with Python

Alice Yang
7 min readDec 12, 2023

--

The find and replace feature in Microsoft Word is a valuable tool that improves efficiency and accuracy when editing or updating documents. Instead of manually searching through lengthy documents, it allows you to swiftly locate and replace specific text or data with remarkable ease and precision. By utilizing this feature, you can save a considerable amount of time and effort, particularly when working with extensive documents. In this article, we will explore how to find and replace text in a Word document using Python.

We will discuss the following topics:

Python Library to Find and Replace Text in Word Documents

To find and replace text in Word documents with Python, we can use the Spire.Doc for Python library.

Spire.Doc for Python is a feature-rich and easy-to-use library for creating, reading, editing, and converting Word files within Python applications. With this library, you can work with a wide range of Word formats, including Doc, Docx, Docm, Dot, Dotx, Dotm, and more. Moreover, you are also able to render Word documents to other types of file formats, such as PDF, RTF, HTML, Text, Image, SVG, ODT, PostScript, PCL, and XPS.

You can install Spire.Doc for Python from PyPI by running the following command in your terminal:

pip install Spire.Doc

For more detailed information about the installation, you can check this official documentation: How to Install Spire.Doc for Python in VS Code.

Find and Replace Text with New Text in Word using Python

When you need to update specific text information throughout a Word document, such as changing names, dates, or contact details, you can use the find and replace feature to quickly replace all instances with new information.

Here is a simple example that shows how to find a specific text and replace all instances of it with another text in Word using Python and Spire.Doc for Python:

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

# Create a Document object
document = Document()
# Load a Word docx or doc document
document.LoadFromFile("Template1.docx")
# document.LoadFromFile("Template1.doc")

# Find a specific text and replace all its instances with another text
document.Replace("Bicycle", "Bike", False, False)

# Save the resulting document
document.SaveToFile("ReplaceAllInstances.docx", FileFormat.Docx2016)
document.Close()
Find and Replace Text with New Text in Word with Python
Find and Replace Text with New Text in Word with Python

In addition to replacing all instances of a specific text, you can replace only the first instance of a specific text by setting the ReplaceFirst property of the Document class to True. Here is a simple example of doing so:

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

# Create a Document object
document = Document()
# Load a Word docx or doc document
document.LoadFromFile("Template1.docx")
# document.LoadFromFile("Template1.doc")

# Enable the ReplaceFirst property to replace only the first instance of a specific text
document.ReplaceFirst = True

# Find a specific text and replace its first instance with another text
document.Replace("Bicycle", "Bike", False, False)

# Save the resulting document
document.SaveToFile("ReplaceFirstInstance.docx", FileFormat.Docx2016)
document.Close()

Find and Replace Text using Regular Expressions (Regex) in Word using Python

Regular expressions provide a powerful way to define search criteria, enabling you to find and replace text that follows a particular pattern or structure.

Here is a simple example that shows how to find and replace text using a regular expression (regex) in Word using Python and Spire.Doc for Python:

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

# Create a Document object
document = Document()
# Load a Word docx or doc document
document.LoadFromFile("Template2.docx")
# document.LoadFromFile("Template2.doc")

# Create a Regex object to match the text within brackets “{}”
regex = Regex("\{.*?\}")

# Replace the matched text with another text
document.Replace(regex, "John Doe")

# Save the resulting document
document.SaveToFile("ReplaceTextUsingRegexPattern.docx", FileFormat.Docx2016)
document.Close()
Find and Replace Text in Word using Regular Expression with Python
Find and Replace Text in Word using Regular Expression with Python

Find and Replace Text with Images in Word using Python

In addition to replacing text with new text, you can replace particular words or phrases with visual content, such as illustrations or logos. This feature is particularly useful when you want to enhance visual appeal or convey information through graphics.

Here is a simple example that shows how to find and replace text with images in Word using Python and Spire.Doc for Python:

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

# Create a Document object
document = Document()
# Load a Word docx or doc document
document.LoadFromFile("Template3.docx")
# document.LoadFromFile("Template3.doc")

# Find the text starting with “//”
selections = document.FindAllPattern(Regex("\/\/.*"))

# Loop through the matched text
for selection in selections:
# Load an image (In this example, the image name is the same as the matched text)
pic = DocPicture(document)
pic.LoadImage("Bikes\\" + selection.SelectedText + ".png")
# Get the matched text as a single text range
textRange = selection.GetAsOneRange()
# Get the index of the text range in its owner paragraph
index = textRange.OwnerParagraph.ChildObjects.IndexOf(textRange)
# Insert an image at the index
textRange.OwnerParagraph.ChildObjects.Insert(index, pic)
# Remove the text range
textRange.OwnerParagraph.ChildObjects.Remove(textRange)

# Save the resulting document
document.SaveToFile("ReplaceTextWithImages.docx", FileFormat.Docx2016)
document.Close()
Find and Replace Text with Image in Word using Python
Find and Replace Text with Image in Word using Python

Find and Replace Text with Tables in Word using Python

In addition to replacing text with new text or images, you can replace text with tabular data.

Here is a simple example that shows how to find and replace text with a table in Word using Python and Spire.Doc for Python:

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

# Create a Document object
document = Document()
# Load a Word docx or doc document
document.LoadFromFile("Template4.docx")
# document.LoadFromFile("Template4.doc")

# Get the first section
section = document.Sections[0]

# Find a specific text in the document
text = document.FindString("Employee_table", False, False)

# Get the paragraph where the found text is located
paragraph = text.GetAsOneRange().OwnerParagraph

# Get the index(zero-based )of the paragraph
body = paragraph.OwnerTextBody
index = body.ChildObjects.IndexOf(paragraph)

# Create a table
table = section.AddTable(True)
table.ResetCells(3, 3)

# Add data to the table
table.Rows[0].Cells[0].AddParagraph().AppendText("Name")
table.Rows[0].Cells[1].AddParagraph().AppendText("Age")
table.Rows[0].Cells[2].AddParagraph().AppendText("Occupation")
table.Rows[1].Cells[0].AddParagraph().AppendText("John")
table.Rows[1].Cells[1].AddParagraph().AppendText("35")
table.Rows[1].Cells[2].AddParagraph().AppendText("Engineer")
table.Rows[2].Cells[0].AddParagraph().AppendText("Sarah")
table.Rows[2].Cells[1].AddParagraph().AppendText("28")
table.Rows[2].Cells[2].AddParagraph().AppendText("Teacher")

table.AutoFit(AutoFitBehaviorType.AutoFitToContents)

# Insert the table at the index of the paragraph
body.ChildObjects.Insert(index, table)
# Remove the paragraph
body.ChildObjects.Remove(paragraph)

# Save the resulting document
document.SaveToFile("ReplaceTextWithTable.docx", FileFormat.Docx2016)
document.Close()
Find and Replace Text with Table in Word with Python
Find and Replace Text with Table in Word with Python

Find and Replace Text with Contents from Another Word Document using Python

You can search for particular words or phrases and replace them with the content from a different document. This feature simplifies the process of merging or importing content from one document to another.

Here is a simple example that shows how to find and replace text with the content from a different Word document using Python and Spire.Doc for Python:

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

# Create a Document object
document = Document()
# Load a Word docx or doc document
document.LoadFromFile("Template5.docx")
# document.LoadFromFile("Template5.doc")

# Load another Word document
loadedDocument = Document("Input.docx")

# Replace a specific text with the Word document
document.Replace("Introduction", loadedDocument, False, False)

# Save the resulting document
document.SaveToFile("ReplaceTextWithDocument.docx", FileFormat.Docx2016)
document.Close()
Find and Replace Text with Another Word Document with Python
Find and Replace Text with Another Word Document with Python

Find and Replace Text inside a Table in Word using Python

When dealing with large or complex tables, manually locating and replacing specific text can be time-consuming and prone to human error. Using the find and replace feature, you can replace specific content with desired content quickly and accurately.

Here is a simple example that shows how to find and replace text inside a table in Word using Python and Spire.Doc for Python:

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

# Create a Document object
document = Document()
# Load a Word docx or doc document
document.LoadFromFile("Template6.docx")
# document.LoadFromFile("Template6.doc")

# Get the first section
section = document.Sections[0]

# Get the first table
table = section.Tables[0]

# Create a dictionary of values
values = {
"#name": "Michael",
"#age": "28",
"#gender": "Male",
"#phone": "01234567",
"#address": "Main Street, USA.",
"#email": "michael@email.com"
}

# Replace text in the table
for key, value in values.items():
table.Replace(key, value, False, True)

# Save the resulting document
document.SaveToFile("ReplaceTextInTable.docx", FileFormat.Docx2016)
document.Close()
Find and Replace Text in Word Table with Python
Find and Replace Text in Word Table with Python

Conclusion

This article demonstrated various scenarios for finding and replacing text in Word documents using Python. We hope you find it helpful.

Related Topics

--

--

Alice Yang

Skilled senior software developers with five years of experience in all phases of software development life cycle using .NET, Java and C++ languages.