How to get PyPDF2 to extract text from multiple sequential pages - in range?

放肆的年华 提交于 2020-01-16 08:39:07

问题


I'm trying to get PyPDF2 to extract specific text throughout a document per the code below. It is pulling exactly what I need and eliminating the duplicates, but it is not getting me a list from each page, it seems to only be showing me the text from the last page. What am I doing wrong?

#import PyPDF2 and set extracted text as the page_content variable
import PyPDF2
pdf_file = open('enme2.pdf','rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()

#for loop to get number of pages and extract text from each page
for page_number in range(number_of_pages):
    page = read_pdf.getPage(page_number)
    page_content = page.extractText()

#initialize the user_input variable
user_input = ""

#function to get the AFE numbers from the pdf document
def get_afenumbers(Y):

    #initialize the afe and afelist variables
    afe = "A"
    afelist = ""
    x = ""

    #while loop to get only 6 digits after the "A"
    while True:

        if user_input.upper().startswith("Y") == True:

                #Return a list of AFE's
                import re
                afe = re.findall('[A][0-9]{6}', page_content)
                set(afe)
                print(set(afe))
                break

        else:
                afe = "No AFE numbers found..."

        if user_input.upper().startswith("N") == True:
            print("HAVE A GREAT DAY - GOODBYE!!!")
            break

#Build a while loop for initial question prompt (when Y or N is not True):
while user_input != "Y" and user_input != "N":
    user_input = input('List AFE numbers? Y or N: ').upper()

    if user_input not in ["Y","N"]:
        print('"',user_input,'"','is an invalid input')

get_afenumbers(user_input)

#FIGURE OUT HOW TO EXTRACT FROM ALL PAGES AND NOT JUST ONE

I'm quite new to this, just learned about regex by a response to my question earlier today. Thanks for any help.


回答1:


If you change a little, it seems works fine.

page_content=""                # define variable for using in loop.
for page_number in range(number_of_pages):
    page = read_pdf.getPage(page_number)
    page_content += page.extractText()     # concate reading pages.


来源:https://stackoverflow.com/questions/49869149/how-to-get-pypdf2-to-extract-text-from-multiple-sequential-pages-in-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!