我正在尝试使用Python和下面的代码将PDF文件转换为CSV。以前它是工作的;但是,最近它不工作。我在转换的CSV文件中获得互换的列内容。
引导我在我的代码中修复此列问题。我只关心PDF转换的第一页,因为我需要删除表的第一行。
#!/usr/bin/env python3
import tabula
import pandas as pd
import csv
pdf_file='/pdf2xls/Input.pdf'
column_names=['Product','Batch No','Machin No','Time','Date','Drum/Bag No','Tare Wt.kg','Gross Wt.kg',
'Net Wt.kg','Blender','Remarks','Operator']
# Page 1 processing
df1 = tabula.read_pdf(pdf_file, pages=1,area=(95,20, 800, 840),columns=[93,180,220,252,310,315,333,367,
410,450,480,520]
,pandas_options={'header': None}) #(top,left,bottom,right)
df1[0]=df1[0].drop(columns=5)
df1[0].columns=column_names
#df1[0].head(2)
#df1[0].to_csv('result.csv')
result = pd.DataFrame(df1[0]) # concate both the pages and then write to CSV
result.to_csv("/pdf2xls/Input.csv")
字符串
2条答案
按热度按时间sqxo8psd1#
假设你的pdf总是至少有两页,最后一页有页脚,你可以试试:
字符串
输出量:
型
2q5ifsrm2#
代码的问题似乎与转换后的CSV文件中的列交换有关。此问题可能是由使用
tabula.read_pdf
时指定列的方式引起的。您可以修改列坐标以确保正确识别和提取每个列。字符串
在此修改后的代码中:
1.我调整了
columns
参数中的列坐标,以确保正确识别每一列。1.我已经使用
df1[0] = df1[0].drop(0)
删除了第一行,以摆脱标题行。1.在将DataFrame保存到CSV时,我添加了
index=False
,以防止将索引作为单独的列写入。