Convert a PDF files to TXT files

好久不见. 提交于 2020-01-14 03:22:07

问题


I need a last touch from an expert !! I want to convert all pdf files in a directory to txt files. I wrote a code to create empty txt files having the same name as pdf files and a code to convert a single pdf to txt but I want to convert all files in the directory. please see the code below: PS : I Already tried with PDFminer, and every other package and it does not work

import pandas as pd
import os
import PyPDF2

###Create empty txt files Named as pdf files ###########

path = '....\\PDF2Text\\PDF\\'
newpath = '....\\PDF2Text\\Text\\'

files = []
for r, d, f in os.walk(path):
    for file in f:
        if '.pdf' in file:
            files.append(os.path.join(r, file))

for f in files:

    ext = f.replace('.pdf','.txt')
    extpath = ext.replace(path,newpath) 

    ft= open(extpath ,"w+")
    ft.close()
    print(extpath)   

 ##Here we Convert a single pdf file to a txt file providing pdf path and empty txt path #####

import PyPDF2

def getPDFFileContentToTXT(pdfFile):
    myPDFFile = PyPDF2.PdfFileReader(pdfFile)

    with open('....\\PDF2Text\\Text\\blabla.txt', 'w') as pdf_output:
       for page in range (myPDFFile.getNumPages()):
           data = myPDFFile.getPage(page).extractText()
           pdf_output.write(data)



   with open('.....\\PDF2Text\\Text\\blabla.txt', 'r') as myPDFContent:
       return myPDFContent.read().replace('\n',' ')

pdfFileContent = getPDFFileContentToTXT('.....\\PDF2Text\\PDF\\blabla.pdf')

回答1:


Have you tried Tika? Just do a pip install tika (also need to have Java 7+ installed on your system) and maybe this is the piece of code you want:

import os
from tika import parser

def read_pdf(pdf_file):

    text = parser.from_file(pdf_file)['content']
    return text.encode('utf-8')

def pdf_to_txt(folder_with_pdf, dest_folder):

"""

folder_with_pdf: path to your pdf's
dest_folder: path where you want .txt files saved

"""

    pdf_files = []

    for root, dirs, files in os.walk(folder_with_pdf):
        for f in files:
            if '.pdf' in f:
                pdf_files.append(os.path.join(root, f))
    #print(pdf_files)

    for file_ in pdf_files:
        text_file = os.path.splitext(os.path.basename(file_))[0]+'.txt'
        with open(os.path.join(dest_folder,text_file), 'wb') as text_f:
            text_f.write(read_pdf(file_))

    return None

pdf_to_txt('./pdf_folder', './txt_folder') #you should see .txt files being populated in ./txt_folder

Aside: If pdf files in sub-directories of ./pdf_folder happens to have the same name (but different content) by any chance, then you will lose one (or more) .txt files.



来源:https://stackoverflow.com/questions/57810749/convert-a-pdf-files-to-txt-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!