我想搜索一个Word 2007文件(.docx)中的文本字符串,例如"some special phrase",这可以在Word中进行搜索。
从Python中是否有一种方法来查看文本?我对格式没有兴趣-我只想将文档分类为具有或不具有"some special phrase"。
# 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')
>>> 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文件(它是一个zip归档文件),然后在“word”文件夹中的“document.xml”文件中查找内容。 如果您想要更加复杂的操作,可以解析XML,但如果您只是想查找短语(您知道不会是标签),那么您只需在XML中查找字符串即可。
<w:p w:rsidR="00C07F31" w:rsidRDefault="003F6D7A">
<w:r w:rsidRPr="003F6D7A">
<w:rPr>
<w:b />
</w:rPr>
<w:t>Hello</w:t>
</w:r>
<w:r>
<w:t xml:space="preserve">World.</w:t>
</w:r>
</w:p>
docx2txt
将docx文件内的文本提取出来,然后在该文本中进行搜索。npm install -g docx2txt
docx2txt input.docx # This will print the text to stdout
docx文件本质上是一个带有XML的zip文件。
XML包含了格式,但也包含了文本。
OLE Automation可能是最简单的。您必须考虑格式,因为文本在XML中可能看起来像这样:
<b>Looking <i>for</i> this <u>phrase</u>
使用简单的文本扫描找到这个并不容易。
您应该能够使用MSWord ActiveX接口来提取要搜索的文本(或者可能进行搜索)。但我不知道如何从Python访问ActiveX。