如何在Word 2007 .docx文件中搜索单词?

84 投票
10 回答
87586 浏览
提问于 2025-04-11 09:18

我想在一个Word 2007文件(.docx格式)中搜索一段文字,比如“某个特殊短语”,这个短语可以在Word里搜索到。

请问有没有办法用Python来查看这个文本?我对格式没有兴趣,只想判断文件里有没有“某个特殊短语”。

10 个回答

21

在这个例子中,“Course Outline.docx”是一个Word 2007文档,它里面包含了“Windows”这个词,但没有“random other string”这个短语。

>>> import zipfile
>>> z = zipfile.ZipFile("Course Outline.docx")
>>> "Windows" in z.read("word/document.xml")
True
>>> "random other string" in z.read("word/document.xml")
False
>>> z.close()

基本上,你只需要用zipfile打开这个docx文件(其实它是一个压缩包),然后在'word'文件夹里的'document.xml'文件中找到内容。如果你想做得更复杂一点,可以解析XML,不过如果你只是想找一个短语(而且你知道它不会是标签),那么直接在XML中查找这个字符串就可以了。

433

在看完你上面的帖子后,我做了一个完全用Python写的docx模块,专门用来解决这个特定的问题。

# Import the module
from docx import document, opendocx

# Open the .docx file
document = opendocx('A document.docx')

# Search returns true if found    
search(document,'your search string')

这个docx模块可以在这里找到:https://python-docx.readthedocs.org/en/latest/

42

更准确地说,.docx文档其实是一个用OpenXML格式压缩的Zip文件:你需要先解压缩它。
我下载了一个示例文件(在谷歌上搜索:某个搜索词 filetype:docx),解压后发现里面有一些文件夹。word文件夹里包含了文档的内容,文件名是document.xml

撰写回答