我试图打开一个zip文件并在zip文件中迭代PDF。我想刮一部分的文本在pdf中。我使用以下代码:
def get_text(part):
#Create path
path = f'C:\\Users\\user\\Data\\Part_{part}.zip'
with zipfile.ZipFile(path) as data:
listdata = data.namelist()
onlypdfs = [k for k in listdata if '_2018' in k or '_2019' in k or '_2020' in k or '_2021' in k or '_2022' in k]
for file in onlypdfs:
with data.open(file, "r") as f:
#Get the pdf
pdffile = pdftotext.PDF(f)
text = ("\n\n".join(pdffile))
#Remove the newline characters
text = text.replace('\r\n', ' ')
text = text.replace('\r', ' ')
text = text.replace('\n', ' ')
text = text.replace('\x0c', ' ')
#Get the text that will talk about what I want
try:
text2 = re.findall(r'FEES (.+?) Types', text, re.IGNORECASE)[-1]
except:
text2 = 'PROBLEM'
#Return the file name and the text
return file, text2然后,在下一行中,我正在运行:
info = []
for i in range(1,2):
info.append(get_text(i))
info我的输出只是第一个文件和文本。我有4个PDF在压缩文件夹。理想情况下,我希望它遍历30+压缩文件。但我有麻烦只有一个。我以前见过这个问题,但解决办法不适合我的问题。是不是和with语句有关?
发布于 2022-04-01 02:41:10
您需要处理所有文件,并在迭代时存储它们。如何这样做的一个例子是将它们存储在一个元组列表中:
file_list = []
for file in onlypdfs:
...
file_list.append((file, text2)
return file_list然后,您可以这样使用:
info = []
for i in range(1,2):
list = get_text(i)
for file_text in list:
info.append(file_text)
print(info)发布于 2022-04-01 02:35:05
当您在这一行:return file, text2上使用返回语句时,退出for循环,跳过您想要读取的其他pdf。
解决方案是将返回语句移到for循环之外。
https://stackoverflow.com/questions/71701113
复制相似问题