Py学习  »  Python

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

acbcccdc • 2 年前 • 471 次点击  

我试图打开一个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

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130510
 
471 次点击  
文章 [ 2 ]  |  最新文章 2 年前
Luke
Reply   •   1 楼
Luke    2 年前

在这一行使用return语句时: return file, text2 ,你退出for循环,跳过你想阅读的其他pdf。

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

ljden
Reply   •   2 楼
ljden    2 年前

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

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)