gpt4 book ai didi

python - 使用 Python 解析 PDF 教科书中的索引页

转载 作者:太空狗 更新时间:2023-10-29 21:02:15 25 4
gpt4 key购买 nike

我必须从 PDF 页面中提取带有缩进的文本到 CSV 文件中。

PDF 教科书的索引页:

我应该将文本连同页码分成类和子类类型层次结构。例如在图像中,Application server 是类,Apache Tomcat 是页码 275 中的子类>

这是 CSV 的预期输出:

我使用 Tika 解析器解析 PDF,但在解析的内容中缩进没有正确维护(不是唯一的)以将文本拆分为类和子类。

解析后的文本是这样的:

谁能建议我满足此要求的正确方法?

最佳答案

尽管我不了解 pdf 提取,但可以从“已解析的文本”重建层次结构,因为“子类”部分总是以额外的换行符开始和结束。

带有以下测试文本:

app architect . 50
app logic . 357
app server . 275

tomcat . 275
websphere . 275
jboss . 164

architect

acceptance . 303
development path . 304

architecting . 48
architectural activity . 25, 320

以下代码:

import csv
import sys
import re


def gen():
is_subclass = False
p_class = None

with open('test.data') as f:
s = f.read()
lines = re.findall(r'[^\n]+\n+', s)
for line in lines:
if ' . ' in line:
class_name, page_no = map(lambda s: s.strip(), line.split('.'))
else:
class_name, page_no = line.strip(), ''

if line.endswith('\n\n'):
if not is_subclass:
p_class = class_name
is_subclass = True
continue

if is_subclass:
yield (p_class, class_name, page_no)
else:
yield (class_name, '', page_no)

if line.endswith('\n\n'):
is_subclass = False


writer = csv.writer(sys.stdout)
writer.writerows(gen())

产量:

app architect,,50
app logic,,357
app server,tomcat,275
app server,websphere,275
app server,jboss,164
architect,acceptance,303
architect,development path,304
architecting,,48
architectural activity,,"25, 320"

希望这对您有所帮助。

关于python - 使用 Python 解析 PDF 教科书中的索引页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49087762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com