Py学习  »  Python

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

acbcccdc • 2 年前 • 476 次点击  

我试图打开一个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
 
476 次点击  
文章 [ 2 ]  |  最新文章 2 年前