Python-text-processing-python-process-word-document

提供:Dev Guides
移動先:案内検索

Python-プロセスWord文書

Wordドキュメントを読むには、docxというモジュールを利用します。 以下に示すように、まずdocxをインストールします。 次に、docxモジュールのさまざまな関数を使用して、ファイル全体を段落ごとに読み取るプログラムを作成します。

以下のコマンドを使用して、docxモジュールを環境に取り込みます。

 pip install docx

以下の例では、各行を段落に追加し、最後にすべての段落テキストを印刷することにより、単語文書の内容を読み取ります。

import docx

def readtxt(filename):
    doc = docx.Document(filename)
    fullText = []
    for para in doc.paragraphs:
        fullText.append(para.text)
    return '\n'.join(fullText)

print (readtxt('path\finddevguides.docx'))

上記のプログラムを実行すると、次の出力が得られます-

Tutorials Point originated from the idea that there exists a class of readers who respond
better to online content and prefer to learn new skills at their own pace from the comforts
of their drawing rooms.

The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated,
we worked our way to adding fresh tutorials to our repository which now proudly flaunts
a wealth of tutorials and allied articles on topics ranging from programming languages
to web designing to academics and much more.

個々の段落を読む

パラグラフ属性を使用して、ワード文書から特定のパラグラフを読み取ることができます。 以下の例では、単語文書から2番目の段落のみを読み取ります。

import docx

doc = docx.Document('path\finddevguides.docx')
print len(doc.paragraphs)

print doc.paragraphs[2].text

上記のプログラムを実行すると、次の出力が得られます-

The journey commenced with a single tutorial on HTML in 2006 and elated by the response
it generated, we worked our way to adding fresh tutorials to our repository
which now proudly flaunts a wealth of tutorials and allied articles on topics
ranging from programming languages to web designing to academics and much more.