迭代多个PDF以提取输出并将其存储在dataframe中

2024-10-02 18:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有>;1000个PDF文件存储在一个目录中。我想从特定页面(第5页和第2页)的表中提取数据。第5页包含两个变量,第2页包含第三个变量

我成功地从一个PDF中提取了变量。但是现在我需要升级我的代码来遍历目录,并对所有PDF执行相同的操作。然后,我需要将输出存储在一个有三列的数据框中。其中,每列表示一个变量,每行表示一个PDF

第5页的表格示例和我要提取的变量 enter image description here

这就是我到目前为止所做的:

import tabula
from tabula import read_pdf
import pandas as pd
from pandas import DataFrame
import re

打开第5页

Page5=tabula.read_pdf("PDF/Sample1.pdf", pages = "5")

#convert to dataframe
Page5DF = pd.DataFrame(Page5[0])

##Variable 1 

#extract variable 1 from the table using index number and column name
ExtractVar1=Page5DF.iloc[31]['Unnamed: 9']

输出:“151دو㶉㶉㶉㶉ن)㶉㶉㶉ن('

#extract the integer from the string
variable1=re.findall(r'\d+', ExtractVar1)

输出:['151']

#convert the list to a single integer 
strings = [str(integer) for integer in variable1]
a_string = "".join(strings)
an_integer = int(a_string)

产出:151

##Variable 2

#extract variable 2 from the table using index number and column name
ExtractVar2=df.iloc[29]['Unnamed: 9']

输出:“162”

#extract the integer from the string using regex
variable2=re.findall(r'\d+', ExtractVar2)

输出:['162']

#convert the list to a single integer 
strings = [str(integer) for integer in variable2]
a_string = "".join(strings)
an_integer = int(a_string)

产出:162

打开第2页

Page2=tabula.read_pdf("PDF/Sample1.pdf", pages = "2")

#convert to dataframe
Page2DF = pd.DataFrame(Page2[0])

#extract ID number from the table using index number and column name
IDNo=Page2DF.iloc[8]['Unnamed: 3']

输出:“10358302”

我尝试将上述代码添加到for循环中,并将输出保存在三个列表中。然后,将列表转换为数据帧中的列。但我无法使其工作。有什么建议吗

# Test

for foldername,subfolders,files in os.walk("./PDF"):
    for file in files:
        #open the PDF file to extract tables 
        Page5=tabula.read_pdf(file, pages = "5")

        #convert to dataframe
        Page5DF = pd.DataFrame(Page5[0])

        #extract variable 1
        ExtractVar1=Page5DF.iloc[31]['Unnamed: 9']
        ExtractVar1

        #extract the integer from the string
        variable1=re.findall(r'\d+', ExtractVar1)
        variable1

        #convert the list to a single integer 
        strings = [str(integer) for integer in variable1]
        a_string = "".join(strings)
        an_integer = int(a_string)

我希望得到的最终输出是如下所示的数据帧

    IDNo    Variable1   Variable2
0   99902   111         323
1   88882   123         543
2   93023   87          72

Tags: thetofromimportconvertforstringpdf