83

I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word.

Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".

edi9999
  • 19,701
  • 13
  • 88
  • 127
Gerry
  • 1,303
  • 1
  • 10
  • 16

10 Answers10

432

After reading your post above, I made a 100% native Python docx module to solve this specific problem.

# 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')

The docx module is at https://python-docx.readthedocs.org/en/latest/

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • 62
    Wait... You wrote an entire module just for this question?! – 11684 Feb 10 '13 at 21:34
  • 54
    @11684 Yes, I had the same problem as the poster, and all I could fine were horrible solutions for invoking .net or Java from Python. – mikemaccana Feb 11 '13 at 10:20
  • 9
    If I knew how to give you my reputation points, I would award them for this -write-a-solution- answer! So I tweeted it instead. MAJOR THANKS! (total time to solve this problem: 25mins, thanks to someone writing the code for me) – Marc Maxmeister Mar 28 '13 at 15:35
  • 29
    I think nailer deserves a meme. "Good guy nailer. Sees that a friend is troubled with a code. Writes a library himself." – Vishwanath Jul 05 '13 at 07:26
  • 3
    Since asterisk imports are an antipattern I'd suggest `from docx import document, opendocx` – mpiskore Feb 13 '19 at 20:49
  • 1
    Although I was searching for a `C++` library, this is really a motivating answer... – Top-Master Apr 30 '19 at 09:45
  • 4
    `opendocx`and `search` doesn't work in Release v0.8.10. I couldn't find any Information about `search`. `opendocx` seems to be now `Document`. – Dirk Schiller Apr 24 '20 at 08:21
  • 2
    What a legend. – Ethan Leyden Mar 14 '23 at 01:26
  • 1
    @MarcMaxmeister Are you along about bounties? https://stackoverflow.com/help/bounty (posting on social media is a win-win though) – Solomon Ucko Mar 14 '23 at 04:22
  • 4
    A post about this on r/programmerhumor has nearly 30k upvotes https://reddit.com/r/ProgrammerHumor/comments/11qbp1x/see_unknow_person_with_a_problem_in_stackoverflow/ – Maarten Mar 14 '23 at 07:15
  • 3
    @Maarten Thanks for the heads up! I've added a response on Reddit under the name "Otherwise-Ad7276". – mikemaccana Mar 14 '23 at 10:08
  • 3
    Before if this got [Historical Lock](https://meta.stackexchange.com/questions/126587/what-is-a-historical-lock-and-what-is-it-used-for) – Ahmed Ali Mar 14 '23 at 12:43
  • gigachad energy – AlexPera Mar 19 '23 at 12:43
42

More exactly, a .docx document is a Zip archive in OpenXML format: you have first to uncompress it.
I downloaded a sample (Google: some search term filetype:docx) and after unzipping I found some folders. The word folder contains the document itself, in file document.xml.

PhiLho
  • 40,535
  • 6
  • 96
  • 134
  • 2
    Ya i get all the xml file.Now i want to ask you that How can we get all the values like (bold,italic ,color,fonname,space ) and all the formatting setting ,How can we get this values from xml. – user1006544 Dec 17 '11 at 10:46
21

In this example, "Course Outline.docx" is a Word 2007 document, which does contain the word "Windows", and does not contain the phrase "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()

Basically, you just open the docx file (which is a zip archive) using zipfile, and find the content in the 'document.xml' file in the 'word' folder. If you wanted to be more sophisticated, you could then parse the XML, but if you're just looking for a phrase (which you know won't be a tag), then you can just look in the XML for the string.

Efren
  • 4,003
  • 4
  • 33
  • 75
Tony Meyer
  • 10,079
  • 6
  • 41
  • 47
  • 5
    It's probably easier to look for the phrase in the element text (using an XML parser) than having to worry about whether part of your text is matched by an element name. – mikemaccana Dec 27 '09 at 12:59
20

A problem with searching inside a Word document XML file is that the text can be split into elements at any character. It will certainly be split if formatting is different, for example as in Hello World. But it can be split at any point and that is valid in OOXML. So you will end up dealing with XML like this even if formatting does not change in the middle of the phrase!

<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>

You can of course load it into an XML DOM tree (not sure what this will be in Python) and ask to get text only as a string, but you could end up with many other "dead ends" just because the OOXML spec is around 6000 pages long and MS Word can write lots of "stuff" you don't expect. So you could end up writing your own document processing library.

Or you can try using Aspose.Words.

It is available as .NET and Java products. Both can be used from Python. One via COM Interop another via JPype. See Aspose.Words Programmers Guide, Utilize Aspose.Words in Other Programming Languages (sorry I can't post a second link, stackoverflow does not let me yet).

romeok
  • 661
  • 1
  • 9
  • 13
5

You can use docx2txt to get the text inside the docx, than search in that txt

npm install -g docx2txt
docx2txt input.docx # This will  print the text to stdout
edi9999
  • 19,701
  • 13
  • 88
  • 127
4

A docx is just a zip archive with lots of files inside. Maybe you can look at some of the contents of those files? Other than that you probably have to find a lib that understands the word format so that you can filter out things you're not interested in.

A second choice would be to interop with word and do the search through it.

kokos
  • 43,096
  • 5
  • 36
  • 32
2

a docx file is essentially a zip file with an xml inside it.
the xml contains the formatting but it also contains the text.

shoosh
  • 76,898
  • 55
  • 205
  • 325
1

OLE Automation would probably be the easiest. You have to consider formatting, because the text could look like this in the XML:

<b>Looking <i>for</i> this <u>phrase</u>

There's no easy way to find that using a simple text scan.

Berkay Turancı
  • 3,373
  • 4
  • 32
  • 45
ilitirit
  • 16,016
  • 18
  • 72
  • 111
0

You should be able to use the MSWord ActiveX interface to extract the text to search (or, possibly, do the search). I have no idea how you access ActiveX from Python though.

Andy Brice
  • 2,297
  • 1
  • 21
  • 28
0

You may also consider using the library from OpenXMLDeveloper.org

billb
  • 3,608
  • 1
  • 32
  • 36