docx, xlsx, pptxファイルからテキストをXMLとして抽出する

MS Office 2007以降のファイル(.docx, .xlsx, .pptx)はZip圧縮されたXMLファイルなので、ファイルからのテキスト抽出などが簡単にできます。


.pptxファイルをZipファイルとして展開すると上記のようになります。
各スライドがXMLファイルとして保存されています。
.docx, .xlsx, .pptxはそれぞれディレクトリ構造が若干違います。
読み取り、もしくは書き込みパスワードが設定されている場合はZipファイルとして解凍はできないようです。

import os.path
import zipfile


def _extract_xmls_from_msxml_base(filepath, prefix):
    xmls = []
    zf = None
    try:
        zf = zipfile.ZipFile(filepath, 'r')
        for name in zf.namelist():
            if name.startswith(prefix):
                xmls.append(zf.read(name))
    except zipfile.BadZipfile, e:
        # for locked files
        print e
    finally:
        if zf is not None:
            zf.close()
    return xmls


def extract_xmls(filepath, ext=None):
    if ext is None:
        root, ext = os.path.splitext(filepath)
    ext = ext.lower()
    prefix = None
    if ext == '.pptx':
        prefix = 'ppt/slides/slide'
    elif ext == '.xlsx':
        prefix = 'xl/worksheets/sheet'
    elif ext == '.docx':
        prefix = 'word/document'

    if prefix is not None:
        return _extract_xmls_from_msxml_base(filepath, prefix)
    return None


def _test():
    print extract_xmls('test.pptx')
    

if __name__ == '__main__':
    _test()