Sunday, December 30, 2012

DOCX Text Mining in Python and Java

In recent years Microsoft has been kind in making its formats easier to parse than binary lumps like the old .doc format. Instead, they now use XML within zip files with the extension .docx. This format can be quickly and easily parsed in Python (see my earlier xlsx parser.)

The Format

Within all new .docx files there is a folder named word and within this folder is a file named document.xml. This has a bunch of <w:t> tags, which hold text. To extract the text, just find those and pull out the contents!

The Code (Python)

#!/usr/bin/env python3
'''

Copyright 2012 Joseph Lewis <joehms22@gmail.com> | <joseph@josephlewis.net>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software recieves a docx file from the command line, and returns the text
from its path.

'''

import zipfile
import xml.dom.minidom
import sys


def extract_docx_text(fp):
myFile = zipfile.ZipFile(fp)

share = xml.dom.minidom.parseString(myFile.read('word/document.xml'))
text = share.getElementsByTagName('w:t')

return " ".join([node.childNodes[0].nodeValue for node in text])

if __name__ == "__main__":
if len(sys.argv) == 1:
print "usage: docx.py FILENAME [FILENAME...]"
else:
for arg in sys.argv:
try:
print(extract_docx_text(arg))
except Exception:
pass # not a valid zipfile, probably.

The Code (Java)

There is an issue with this Java implementation, but it should work for most purposes: special characters that are escaped in xml, like &amp; will not be unescaped in processing.
/**

Copyright 2012 Joseph Lewis <joehms22@gmail.com> | <joseph@josephlewis.net>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This software recieves a docx file from the command line, and returns the text
from its path.

**/
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class DOCXExtracter {
private static String convertStreamToString(java.io.InputStream is) {
try(Scanner s = new java.util.Scanner(is).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : "";
}
}

public static String extractFromPath(String path) throws IOException
{
ZipFile zipFile = new ZipFile(path);
String ret = extractFromFile(zipFile);
zipFile.close();
return ret;
}

public static String extractFromFile(ZipFile f) throws IOException
{
ZipEntry e = f.getEntry("word/document.xml");
InputStream is = f.getInputStream(e);
String contents = convertStreamToString(is);
is.close();
return contents.replaceAll("(?s)\\<.*?\\>", " ");
}

public static void main(String[] args)
{
for(int i = 0; i < args.length; i++)
try {
System.out.println(extractFromPath(args[i]));
} catch (IOException e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment