问题描述
我在一个目录中存储了 1000 个以上的 PDF 文件。我想从特定页面(第 5 页和第 2 页)中的表中提取数据。第 5 页包含两个变量,第 2 页包含第三个变量。
我成功地从一个 PDF 中提取了变量。但是现在我需要升级我的代码以遍历目录并对所有 PDF 执行相同的操作。然后,我需要将输出存储在具有三列的数据框中。其中每一列代表一个变量,每一行代表一个 PDF。
第 5 页上的表格样本和我想提取的变量
这是我目前所做的:
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\rدوران ازون )بالأيام('
#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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)