Python
 Computer >> コンピューター >  >> プログラミング >> Python

PythonでPDFファイルを操作しますか?


Pythonは、さまざまな要件に対応するための膨大なライブラリセットを提供するため、非常に用途の広い言語です。私たちは皆、Portable Document Format(PDF)ファイルに取り組んでいます。 Pythonは、PDFファイルを操作するためのさまざまな方法を提供します。ここでは、PyPDF2というPythonライブラリを使用してPDFファイルを操作します。

PyPDF2は、PDFファイルのページを分割、マージ、トリミング、および変換できる純粋なPythonPDFライブラリです。また、カスタムデータ、表示オプション、およびパスワードをPDFファイルに追加することもできます。 PDFからテキストとメタデータを取得したり、ファイル全体をマージしたりできます。

PyPDF2を使用してPDFに対して複数の操作を実行できるため、スイスアーミーナイフのように機能します。

はじめに

pypdf2は標準のPythonパッケージであるため、インストールする必要があります。良い点は、非常に簡単なことです。pipを使用してインストールできます。コマンド端末で以下のコマンドを実行するだけです:

C:\Users\rajesh>pip install pypdf2
Collecting pypdf2
Downloading https://files.pythonhosted.org/packages/b4/01/68fcc0d43daf4c6bdbc6b33cc3f77bda531c86b174cac56ef0ffdb96faab/PyPDF2-1.26.0.tar.gz (77kB)
100% |████████████████████████████████| 81kB 83kB/s
Building wheels for collected packages: pypdf2
Building wheel for pypdf2 (setup.py) ... done
Stored in directory: C:\Users\rajesh\AppData\Local\pip\Cache\wheels\53\84\19\35bc977c8bf5f0c23a8a011aa958acd4da4bbd7a229315c1b7
Successfully built pypdf2
Installing collected packages: pypdf2
Successfully installed pypdf2-1.26.0

確認するには、Pythonシェルからpypdf2をインポートします

>>> import PyPDF2
>>>
Successful, Great.

メタデータの抽出

重要な有用なデータのいくつかを任意のPDFから抽出できます。たとえば、ドキュメントの作成者、タイトル、件名、PDFファイルに含まれるページ数に関する情報を抽出できます。

以下は、pypdf2パッケージを使用してpdfファイルから有用な情報を抽出するPythonプログラムです。

from PyPDF2 import PdfFileReader
def extract_pdfMeta(path):
   with open(path, 'rb') as f:
      pdf = PdfFileReader(f)
      info = pdf.getDocumentInfo()
      number_of_pages = pdf.getNumPages()
   print("Author: \t", info.author)
   print()
   print("Creator: \t", info.creator)
   print()
   print("Producer: \t",info.producer)
   print()
   print("Subject: \t", info.subject)
   print()
   print("title: \t",info.title)
   print()
   print("Number of Pages in pdf: \t",number_of_pages)
if __name__ == '__main__':
   path = 'DeepLearning.pdf'
   extract_pdfMeta(path)

出力

Author: Nikhil Buduma,Nicholas Locascio

Creator: AH CSS Formatter V6.2 MR4 for Linux64 : 6.2.6.18551 (2014/09/24 15:00JST)

Producer: Antenna House PDF Output Library 6.2.609 (Linux64)

Subject: None

title: Fundamentals of Deep Learning

Number of Pages in pdf: 298

したがって、PDFファイルを開かなくても、PDFファイルからいくつかの有用な情報を取得できます。

PDFからのテキストの抽出

PDFからテキストを抽出できます。画像抽出のサポートが組み込まれていますが。

上でダウンロードしたpdfファイルの特定のページ(例:50ページ)からテキストを抽出してみましょう。

#Import pypdf2
from PyPDF2 import PdfFileReader
def extract_pdfText(path):
   with open(path, 'rb') as f:
      pdf = PdfFileReader(f)
      # get the 50th page
      page = pdf.getPage(50)
      print(page)
      print('Page type: {}'.format(str(type(page))))
      #Extract text from the 50th page
      text = page.extractText()
      print(text)
if __name__ == '__main__':
   path = 'DeepLearning.pdf'
   extract_pdfText(path)

出力

{'/Annots': IndirectObject(1421, 0),
'/Contents': IndirectObject(179, 0),
'/CropBox': [0, 0, 595.3, 841.9],
'/Group': {'/CS': '/DeviceRGB', '/S': '/Transparency', '/Type': '/Group'},
'/MediaBox': [0, 0, 504, 661.5],
'/Parent': IndirectObject(4863, 0),
'/Resources': IndirectObject(1423, 0),
'/Rotate': 0,
'/Type':
'/Page'
}

Page type: <class 'PyPDF2.pdf.PageObject'>
time. In inverted dropout, any neuron whose activation hasn†t been silenced has its
output divided by p before the value is propagated to the next layer. With this
fix, Eoutput=p⁄xp+1ƒ
p⁄0=
x, and we can avoid arbitrarily scaling neuronal
output at test time.

SummaryIn this chapter, we†ve learned all of the basics involved in training feed-forward neural
networks. We†ve talked about gradient descent, the backpropagation algorithm, as
well as various methods we can use to prevent overfitting. In the next chapter, we†ll
put these lessons into practice when we use the TensorFlow library to efficiently
implement our first neural networks. Then in
Chapter 4

, we†ll return to the problem
of optimizing objective functions for training neural networks and design algorithmsto significantly improve performance. These improvements will enable us to process
much more data, which means we†ll be able to build more comprehensive models.
Summary | 37

50ページからテキストを取得することはできますが、それほどきれいではありません。残念ながら、pypdf2はPDFからテキストを抽出するためのサポートが非常に限られています。

PDFファイルの特定のページを回転させる

>>> import PyPDF2
>>> deeplearningFile = open('DeepLearning.pdf', 'rb')
>>> pdfReader = PyPDF2.PdfFileReader(deeplearningFile)
>>> page = pdfReader.getPage(0)
>>> page.rotateClockwise(90)
{
'/Contents': [IndirectObject(4870, 0), IndirectObject(4871, 0), IndirectObject(4872, 0), IndirectObject(4873, 0), IndirectObject(4874, 0), IndirectObject(4875, 0), IndirectObject(4876, 0), IndirectObject(4877, 0)],

'/CropBox': [0, 0, 595.3, 841.9],

'/MediaBox': [0, 0, 504, 661.5], '/Parent': IndirectObject(4862, 0), '/Resources': IndirectObject(4889, 0),
'/Rotate': 90,
/Type': '/Page'
}
>>> pdfWriter = PyPDF2.PdfFileWriter()
>>> pdfWriter.addPage(page)
>>> resultPdfFile = open('rotatedPage.pdf', 'wb')
>>> pdfWriter.write(resultPdfFile)
>>> resultPdfFile.close()
>>> deeplearningFile.close()

出力

PythonでPDFファイルを操作しますか?


  1. Pythonの内部動作

    この記事では、Pythonの内部動作と、Pythonインタープリターによってさまざまなオブジェクトがメモリ内のスペースに割り当てられる方法について学習します。 Pythonは、Javaのようなオブジェクト指向プログラミング構築言語です。 Pythonはインタプリタを使用するため、インタプリタ言語と呼ばれます。 Pythonは、読みやすさを向上させ、時間とスペースの複雑さを最小限に抑えるために、ミニマリズムとモジュール性をサポートしています。 Pythonの標準実装は「cpython」と呼ばれ、cコードを使用してPythonで出力を取得できます。 Pythonは、ソースコードを一連のバイトコ

  2. Pythonで画像を操作しますか?

    最も人気があり、画像処理用のPythonのデフォルトライブラリと見なされているものの1つは、Pillowです。 Pillowは、Python Image LibraryまたはPILの更新バージョンであり、さまざまなシンプルで高度な画像操作機能をサポートしています。これは、sciPyやMatplotlibなどの他のPythonライブラリでの単純な画像サポートの基礎でもあります。 枕の取り付け 始める前に、Pythonと枕が必要です。 Linuxの場合、Fedora、Debian / Ubuntu、ArchLinuxなどのLinuxの主要なフレーバーには、以前はPILが含まれていたパッケージにP