如何在Python的Camelot库中传入自定义表格区域参数提取PDF表格
问题修正点
- 原代码中
table_areas参数传入的是固定字符串'x1,x2,x3,x4',没有读取用户输入的坐标变量 - 重复调用
camelot.read_pdf两次,第一次读取无实际作用,可删除 - 错误将
index、ignore_index参数放到camelot.read_pdf中,这两个参数属于to_excel方法,传入camelot读取方法会触发参数报错 - camelot的
table_areas参数要求传入格式为["x1,y1,x2,y2"]的字符串列表,四个值分别对应表格区域的左、上、右、下坐标
修正后代码
import camelot import pandas as pd # 读取用户输入 pdf_line = input("Enter pdf path: ") x1 = input("Enter coordinate x1: ") y1 = input("Enter coordinate y1: ") x2 = input("Enter coordinate x2: ") y2 = input("Enter coordinate y2: ") # 拼接符合camelot要求的table_areas参数 table_area_str = f"{x1},{y1},{x2},{y2}" # 读取PDF指定区域的表格 tables = camelot.read_pdf(pdf_line, flavor='stream', table_areas=[table_area_str]) # 输出结果并导出为Excel print(tables[0].df) tables[0].to_excel("1.xlsx", index=False)
如果需要导出为CSV,把最后一行的to_excel替换为to_csv即可,示例:
tables[0].to_csv("1.csv", index=False, encoding="utf-8-sig")
内容的提问来源于stack exchange,提问作者vidushi kothari
相关产品推荐
相关产品推荐

