【发布时间】:2022-07-20 01:49:31
【问题描述】:
使用 pdfplumber 库,您可以提取 PDF 页面的文本,也可以从 pdf 页面中提取表格。
问题是我似乎找不到提取文本和表的方法。本质上,如果pdf以这种方式格式化:
text1
tablename
___________
| Header 1 |
------------
| row 1 |
------------
text 2
我希望输出是:
["text 1",
"table name",
[["header 1"], ["row 1"]],
"text 2"]
在本例中,您可以从 pdfplumber 运行 extract_text:
with pdfplumber.open("example.pdf") as pdf:
for page in pdf.pages:
page.extract_text()
但这会将文本和表格提取为文本。您可以运行 extract_tables,但这只会为您提供表格。我需要一种同时提取文本和表格的方法。
这是以某种我不理解的方式内置到库中的吗?如果没有,这可能吗?
编辑:已回答
这直接来自已接受的答案,稍作调整即可修复它。非常感谢!
from operations import itemgetter
def check_bboxes(word, table_bbox):
"""
Check whether word is inside a table bbox.
"""
l = word['x0'], word['top'], word['x1'], word['bottom']
r = table_bbox
return l[0] > r[0] and l[1] > r[1] and l[2] < r[2] and l[3] < r[3]
tables = page.find_tables()
table_bboxes = [i.bbox for i in tables]
tables = [{'table': i.extract(), 'top': i.bbox[1]} for i in tables]
non_table_words = [word for word in page.extract_words() if not any(
[check_bboxes(word, table_bbox) for table_bbox in table_bboxes])]
lines = []
for cluster in pdfplumber.utils.cluster_objects(
non_table_words + tables, itemgetter('top'), tolerance=5):
if 'text' in cluster[0]:
lines.append(' '.join([i['text'] for i in cluster]))
elif 'table' in cluster[0]:
lines.append(cluster[0]['table'])
2022 年 7 月 19 日编辑:
更新了一个参数以包含 itemgetter,它现在是 pdfplumber 的 cluster_objects 函数所必需的(而不是字符串)
【问题讨论】:
-
对于以后来这里的人来说,值得注意的是,这种方法只有在表格左右没有文字的情况下才有效。
标签: python pdf pdfplumber