[英]Python PDF Scraping
PDF 是銀行對賬單,包含列,即(日期、描述、存款、取款、余額),用各自的字段解析列,並以 CSV 格式導出該數據。 PDF 。
import pdftotext
import re
import csv
# open PDF file
with open('test.pdf', 'rb') as pdf_file:
pdf = pdftotext.PDF(pdf_file)
# extract tabular text
lines = pdf[2].split('\n')[4:]
# CSV table
table = []
# loop over lines in table
for line in lines:
# replace trailing spaces with comas
row = re.sub(' ', ',', line)
# reducing the number of comas to one
row = [cols.strip() for cols in re.sub(',+', ',', row).split(',')]
# handling missed separators
row = ','.join(row).replace(' ', ',').split(',')
# append row to table
table.append(row)
print(table)
# write CSV output
with open('test.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerows(table)
我沒有得到想要的 output 即描述的一半顯示在日期表下。我附上csv以供進一步參考。
例如
['04/02','克萊斯勒資本支付 0023582513','$469.88-','$51.15']
你可以使用 pdfplumber 庫,它非常有用,我得到這個 output 不到五分鍾,它需要使用表參數
import pandas as pd
import pdfplumber
pdf = pdfplumber.open(r'C:\Users\Erkin\Downloads\test.pdf')
df = pd.DataFrame()
table_settings={"vertical_strategy": "text",
"horizontal_strategy": "lines","intersection_y_tolerance": 8}
df = pd.DataFrame(pdf.pages[3].extract_table(table_settings))
df.to_csv(r'C:\Users\Erkin\Downloads\test.csv')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.