当你需要在长文档或报告中快速找到特定的关键词或短语,Word中提供的查找并高亮这一功能可以帮助你迅速定位这些内容。本文将介绍如何使用Python在Word中查找并突出显示指定的文本。
所需工具:第三方库 Spire.Doc for Python。该库支持创建、编辑、转换Word文档等多种操作,可以通过以下pip命令安装:
pip install Spire.Doc
示例代码如下:
- from spire.doc import *
- from spire.doc.common import *
-
- inputFile = "示例.docx"
- outputFile = "查找并高亮.docx"
-
- # 创建一个Document对象
- document = Document()
-
- # 加载一个Word文档
- document.LoadFromFile(inputFile)
-
- # 查找文档中所有的指定文本
- textSelections = document.FindAllString("归纳", False, True)
-
- # 遍历所有匹配文本
- for selection in textSelections:
- # 获取匹配文本的文本范围
- textRange = selection.GetAsOneRange()
- # 设置高亮颜色
- textRange.CharacterFormat.HighlightColor = Color.get_Yellow()
-
- # 保存结果文件
- document.SaveToFile(outputFile, FileFormat.Docx2016)
- document.Close()
输出结果:

以上示例演示了使用Python在Word中查找并突出显示所有匹配的指定文本。如果你只需要查找并突出显示第一个匹配的文本,可以使用Spire.Doc for Python库提供的Document.FindString(matchString: str, caseSensitive: bool, wholeWord: bool) 方法。
代码片段:
- # 查找第一个匹配的指定文本
- textSelection = document.FindString("归纳", False, True)
- # 获取其文本范围
- textRange = textSelection.GetAsOneRange()
- # 设置高亮颜色
- textRange.CharacterFormat.HighlightColor = Color.get_Yellow()
输出结果:

了解更多使用Python处理Word文档的示例教程,请前往: