Search code examples
pythontextdata-extractionpdftotext

Extracting particular data using pdftotext


I am using pdftotext Python Library to extract some data from a PDF Document.

import pdftotext

# Load your PDF
with open("text2.pdf", "rb") as f:
    pdf = pdftotext.PDF(f)


# How many pages?
print(len(pdf))



data = "\n\n".join(pdf)
# Read all the text into one string
print(data)

The data extracted is:

Account Name               :Mr. SX
Account Name               :Mr. XX XX XX
Address                  : Address detaisls
                      
Date                        :7 Sep 2021
Account Number               :00000031873583221
Account Description          :REGULAR SB CHQ-INDIVIDUALS
Branch                      :SSI 
Drawing Power               :0.00

The whole data is in string but I want to extract only the Account Number. I used regex expresion:

^(Account\s+Number).*$

But unable to figure out how to extract the data from the whole string.


Solution

  • You could try:

    >>> '\n'.join([re.sub(r'Account Number\s+:', '', line) for line in data.splitlines() if 'Account Number' in line])
    '00000031873583221'
    >>> 
    

    Easier without regex:

    >>> '\n'.join([line.split(':')[-1] for line in data.splitlines() if 'Account Number' in line])
    '00000031873583221'
    >>>