使用 Python 将 PDF 转换为 Dataframe

新手上路,请多包涵
阅读 1k
1 个回答

我找到了出路。我正在使用 Tabula-py 绑定和 PyPDF2。

我正在使用 PyPDF2 获取 PDF 中的页数并使用它遍历 .pdf 文件的每一页。

并且,Tabula 用于提取数据并将其转换为数据框。

如果有更好的方法,请更正。

 import pandas as pd
import numpy as np
from tabula import read_pdf_table
import PyPDF2

reader = PyPDF2.PdfFileReader(open('Your Path', mode='rb'))
m = reader.getNumPages()
#print(reader)
print(m)
for i in range(m):
    n = i+1

    if n==1:
        df = read_pdf_table('Your Path', pandas_options={'header': None, 'error_bad_lines': False}, pages=n)
        index = np.where(df[0].isnull())[0]
        sect = df.iloc[index[0]:index[-1]]
        s = []
        headers = []
        for col in sect:
            colnames = sect[col].dropna().values.flatten()
            (s.insert(len(s), colnames))
            pic = [' '.join(s[col])]
            for i in pic:
                headers.append(i)
        print(df)
        df.drop(sect, inplace=True)
        df.columns = headers
        new_df = pd.DataFrame(columns=headers)
        new_df = pd.concat([new_df, df], axis=0, ignore_index=True)

    else:
        df_2 = read_pdf_table('Your Path', pandas_options={'header': None, 'error_bad_lines': False, 'encoding': "ISO-8859-1"}, pages=n)
        df_2.drop(sect, inplace=True)
        df_2.columns = headers
        new_df = pd.concat([new_df, df_2], axis=0, ignore_index=True)

new_df.columns = headers
print(new_df)
new_df.to_csv('Your Path', index=False)

原文由 Saurabh Pore 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进