Python-text-processing-python-process-pdf

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

Python-プロセスPDF

Pythonは、PDFファイルを読み取り、そこからテキストを抽出した後にコンテンツを印刷できます。 そのためには、最初に PyPDF2 である必要なモジュールをインストールする必要があります。 以下は、モジュールをインストールするコマンドです。 Python環境にpipが既にインストールされている必要があります。

pip install pypdf2

このモジュールが正常にインストールされると、モジュールで使用可能なメソッドを使用してPDFファイルを読み取ることができます。

import PyPDF2

pdfName = 'path\finddevguides.pdf'
read_pdf = PyPDF2.PdfFileReader(pdfName)
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content

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

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.

複数のページを読む

複数のページでpdfを読み取り、ページ番号で各ページを印刷するには、getPageNumber()関数でループを使用します。 以下の例では、2ページのPDFファイルを作成します。 内容は2つの個別のページ見出しの下に印刷されます。

import PyPDF2

pdfName = 'Path\finddevguides2.pdf'
read_pdf = PyPDF2.PdfFileReader(pdfName)

for i in xrange(read_pdf.getNumPages()):
    page = read_pdf.getPage(i)
    print 'Page No - ' + str(1+read_pdf.getPageNumber(page))
    page_content = page.extractText()
    print page_content

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

Page No - 1
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.


Page No - 2

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 p
rogramming languages to web
designing to academics and much more.