使用PyPDF2从pdf提取文本

时间:2019-01-19 00:03:51

标签: pdf ocr text-extraction pypdf2 ner

我的任务是从目录中读取pdf文件(扫描的文件,文本或其他格式的文件)和大约600个文件,并从中获取文本。对于图像或其他东西,我必须构建一个可以识别其中文本的OCR。有些文件是安全的,无法解密(可能是pypdf2的缺点,因为我尝试使用“”进行解密)。我现在停留的是从pdf文件中提取所有文本,并且当点击的文件名无法提取时,我的代码进入了一个无休止的循环。如何以这种或任何其他方式最好地解决此问题的方式提取所有普通文本或同时使用OCR。最终目标是(最有可能)创建带有产品名称的pdf标记的NER模型,以便为其制作培训样本,并且一旦从pdf文本中删除了产品名称,便会对其进行标记。下面附上代码以供参考。谢谢

import PyPDF2
from os import listdir
from os.path import isfile, join
#pdfFileObj = open('C:/Users/Lenovo/.spyder-py3/OCR', 'rb')
mypath ='C:/Users/Lenovo/.spyder-py3/OCR'
path = 'C:/Users/Lenovo/.spyder-py3/OCR/'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in onlyfiles:
    fileReader = PyPDF2.PdfFileReader(open((path+file),'rb'))
    print(file)
    count = 0
    if fileReader.isEncrypted == False:
        while count < 3:
            try:

                print(count)
                print(fileReader.isEncrypted)
        #        fileReader.decrypt("")
                pageObj = fileReader.getPage(count)
                count +=1
                text = pageObj.extractText()
                print(text)
            except IndexError:

                print(count,file)
        continue

0 个答案:

没有答案