PDF抓取:如何为Python中抓取的每个PDF自动创建txt文件?

PDF抓取:如何为Python中抓取的每个PDF自动创建txt文件?,python,loops,pdf,pdfminer,Python,Loops,Pdf,Pdfminer,我想做的是:一个程序,它将一个pdf文件列表作为输入,并为列表中的每个文件返回一个.txt文件 例如,给定一个listA=[“file1.pdf”、“file2.pdf”、“file3.pdf”],我希望Python创建三个txt文件(每个pdf文件一个),比如“file1.txt”、“file2.txt”和“file3.txt” 我有转换部分顺利工作感谢。我所做的唯一更改是在maxpages语句中,在该语句中我指定了1而不是0,以便只提取第一页。正如我所说,我的代码的这一部分工作得非常好。这是

我想做的是:一个程序,它将一个pdf文件列表作为输入,并为列表中的每个文件返回一个.txt文件

例如,给定一个listA=[“file1.pdf”、“file2.pdf”、“file3.pdf”],我希望Python创建三个txt文件(每个pdf文件一个),比如“file1.txt”、“file2.txt”和“file3.txt”

我有转换部分顺利工作感谢。我所做的唯一更改是在maxpages语句中,在该语句中我指定了1而不是0,以便只提取第一页。正如我所说,我的代码的这一部分工作得非常好。这是密码

def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = file(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
#maxpages = 0
maxpages = 1
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
    interpreter.process_page(page)
fp.close()
device.close()
str = retstr.getvalue()
retstr.close()
return str
问题是我似乎不能让Python返回我,这是我在第二段中所说的。我尝试了以下代码:

def save(lst):
i = 0

while i < len(lst):
    txtfile = "enegep"+str(i)+".txt" #enegep is like the identifier of the files
    artigo = convert_pdf_to_txt(lst[0])
    with open(txtfile, "w") as textfile:
        textfile.write(artigo)
    i += 1
def保存(lst):
i=0
而i

我使用两个pdf文件的列表作为输入来运行save函数,但它只生成了一个txt文件,并持续运行了几分钟,而没有生成第二个txt文件。实现我的目标的更好方法是什么?

您不更新
i
,因此您的代码陷入无限循环,您需要
i+=1

def save(lst):
    i = 0   # set to 0 but never changes
    while i < len(lst):
        txtfile = "enegep"+str(i)+".txt" #enegep is like the identifier of the files
        artigo = convert_pdf_to_txt(lista[0])
        with open(txtfile, "w") as textfile:
            textfile.write(artigo)
     i += 1 # you need to  increment i
您也只能使用
lista[0]
,因此您可能还需要更改该代码,以便在每次迭代中在列表中移动帐户

如果lst实际上是lista,则可以使用
枚举

   def save(lst):
        for i, ele in enumerate(lst): 
            txtfile = "enegep{}.txt".format(i) #enegep is like the identifier of the files
            artigo = convert_pdf_to_txt(ele)
            with open(txtfile, "w") as textfile:
                textfile.write(artigo)

很抱歉,我在这里发布之前没有意识到我的代码有一些拼写错误和小错误。我刚修好。顺便说一句,“lista”在葡萄牙语中的意思是列表。编辑:第二个很好地工作,非常感谢。@iatowks,您仍然需要使用比lista[0]更多的内容,您确定i+=1的位置正确吗?尝试我提供的最后一个代码我使用了您在我的代码中编写的第三个选项,它给了我预期的结果。再次感谢你,没问题。很高兴这有帮助
   def save(lst):
        for i, ele in enumerate(lst): 
            txtfile = "enegep{}.txt".format(i) #enegep is like the identifier of the files
            artigo = convert_pdf_to_txt(ele)
            with open(txtfile, "w") as textfile:
                textfile.write(artigo)