我被这个问题卡住了。我不一定在这里寻找代码片段,但可能是一个更高层次的概念,我试图做什么可以工程。
我有一个不同类型的PDF文件列表。不同的类型包含的信息不同,格式也不同。基于PDF的类型,我需要从它们中提取不同的信息。为此,我使用了两个Python库,它们允许我以不同的方式从PDF文件中提取数据。
问题是,例如,我可以通过查看数据帧中的索引10来识别PDF_1,而在读取PDF_2时,没有索引10,所以我得到了一个IndexError。
现在,我的暴力解决方案是做一些类似下面的事情。但这是不可行的,因为实际上我有更多类型的PDF文件,这是非常不可伸缩/不可靠的
for file in os.listdir("all file"):
if file.endswith(".pdf"):
content = tab.read_pdf('file/'+file, pages='all', guess=False, stream=True)
# checks for PDF_1
try:
if content[1].columns[10] == 'String identifying PDF 1':
extract_pdf_1()
print(file + ' is pdf 1')
# checks for PDF_2
except:
try:
if content.loc[4].str.contains("String identifying PDF 2").all():
extract_pdf_2()
print(file + ': is pdf 2')
except:
print('pdf not recognised')发布于 2020-07-07 21:40:29
可以这样做:
def check_pdf_1(content):
try:
if content[1].columns[10] == 'String identifying PDF 1':
return True
except SpecException as e:
return False
...
pdf_handlers= {
1: (check_pdf_1, extract_pdf_1),
2: (check_pdf_2, extract_pdf_2),
}
...
for file in os.listdir("all file"):
if file.endswith(".pdf"):
content = tab.read_pdf('file/' + file, pages='all', guess=False, stream=True)
for check_pdf, extract_pdf in pdf_handlers.values():
if check_pdf(content):
extract_pdf(content)
break 发布于 2020-07-07 22:08:07
您可以创建不同的函数来识别每种类型的pdf,如果找到,则返回"true“或"false”。此外,您还需要另一个函数来调用每个check-type,直到找到一个"true“返回值。你不需要嵌套的try-check,你可以在每个函数上将它们分开(让它们都在同一个级别上)。
def check1():
try:
if content[1].columns[10] == 'String identifying PDF 1':
extract_pdf_1()
print(file + ' is pdf 1')
except:
return False
def check2():
try:
if content.loc[4].str.contains("String identifying PDF 2").all():
extract_pdf_2()
print(file + ': is pdf 2')
except:
return False
def checks(content):
if (check1(content)):
return
if (check2(content)):
return
for file in os.listdir("all file"):
if file.endswith(".pdf"):
content = tab.read_pdf('file/'+file, pages='all', guess=False, stream=True)
checks(content) https://stackoverflow.com/questions/62776341
复制相似问题