Python:For循环只迭代一次,也使用with语句



我正在尝试打开一个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 = ("nn".join(pdffile))

#Remove the newline characters
text = text.replace('rn', ' ')
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

我的输出只是第一个文件和文本。我在zip文件夹中有4个PDF。理想情况下,我希望它能遍历30多个zip文件。但我有一个问题。我以前见过有人问我这个问题,但解决方案不适合我的问题。是和with语句有关吗?

您需要处理所有文件,并在迭代时存储每个文件。如何做到这一点的一个例子是将它们存储在元组列表中:

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)

当您在以下行使用return语句:return file, text2时,您将退出for循环,跳过要读取的其他pdf。

解决方案是将return语句移到for循环之外。

最新更新