Search code examples
python-3.xdataframepdftabula

How to extract specific pages based on a formula?


I'm trying to extract pages from a PDF that is 1000 pages long but I only need pages in the pattern of [9,10,17,18,25,26,33,34,...etc]. These numbers can be represented in the formula: pg = 1/2 (7 - 3 (-1)^n + 8*n).

I tried to define the formula and plug into tabula.read_pdf but I'm not sure how to define the 'n' variable where 'n' ranges from 0 up to 25. Right now I defined it as a list which I think is the problem...

n = list(range(25+1))
pg = 1/2 (7 - 3 (-1)^n + 8*n) 

df = tabula.read_pdf(path, pages = 'pg',index_col=0, multiple_tables=False)

When trying to execute, I get a TypeError: 'int' object is not callable on line pg = 1/2 (7 - 3 (-1)^n + 8*n). How would I define the variables so that tabula extracts pages that fit the condition of the formula?


Solution

  • Formula is x = 1/2(8n - 3(-1)^n + 7)

    Step1:

    pg = []  #Empty list to store the pages numbers calculated by formula
    for i in range(1, 25+1):     # For 1000 pages pdf use 1000 instead of 25
        k = int(1/2*((8*n[i])-3*((-1)**n[i])+7))
        pg.append(k)
    
    print(pg, end = '')  # This will give you list of page numbers
    
    #[9, 10, 17, 18, 25, 26, 33, 34, 41, 42, 49, 50, 57, 58, 65, 66, 73, 74, 81, 82, 89, 90, 97, 98, 105]
    

    Step 2:

    # Now run the loop through each of the pages with the table
    
    df=pd.DataFrame([])
    df_combine=pd.DataFrame([])
    
    for pageiter in range(pg):
                df = tabula.read_pdf(path, pages=pageiter+1 ,index_col=0, multiple_tables=False, guess=False) #modify it as per your requirement
                df_combine=pd.concat([df,df_combine]) #you can choose between merge or concat as per your need
    

    OR

    df_data = []
    for pageiter in range(pg):
                df = tabula.read_pdf(path, pages=pageiter+1 ,index_col=0, multiple_tables=False, guess=False) #modify it as per your requirement
                df_data.append(df)
    
    df_combine= pd.concat(df_data, axis=1)
    

    Reference link to create formula https://www.wolframalpha.com/widgets/view.jsp?id=a3af2e675c3bfae0f2ecce820c2bef43