如何让PyPDF2从多个连续页面中提取文本 - 在范围内?

时间:2018-04-17 02:54:35

标签: regex python-3.x pypdf2

我正在尝试让PyPDF2根据下面的代码提取整个文档中的特定文本。它正在提取我所需要的并消除重复项,但它并没有从每个页面获取一个列表,它似乎只显示了最后一页的文本。我做错了什么?

#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

我对此很陌生,刚刚通过今天早些时候对我的问题的回答了解了正则表达式。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

如果你稍微改变一下,似乎工作正常。

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.