[英]PyPDF2 - PdfFileReader - cannot extract text
我正在循环浏览一个目录并阅读大量 PDF。 我正在使用循环从每个页面中提取所有文本信息。
5/13 PDF 在尝试使用时抛出错误。getNumPages(): 发生异常: ValueError 无效的 int() 字面量为 10: b''。 我相信发生此错误是因为 object (PyPDF2) 显示 numPages: 0。
dir = os.listdir(directory)
for f in dir:
object = PyPDF2.PdfFileReader(directory + '\\' + f)
NumPages = object.getNumPages()
text_output = "" # Initiate Variable
# Loop through all pages and extract/merge text
with open(directory + '\\' + f, mode='rb') as FileName:
reader = PyPDF2.PdfFileReader(FileName)
for p_num in range(0, NumPages):
page = reader.getPage(p_num)
text_output = text_output + '\n' + 'PAGE: ' + \
str(p_num + 1) + '\n' + page.extractText()
我添加了一张显示 object 数据的图像,其中 numPages: 0
我不明白为什么只有某些 PDF 有这个问题。 任何帮助,将不胜感激!!
我测试了几个 pdf 库,我注意到PyMuPDF最适合阅读 pdf 文件。
这里的代码示例:
import fitz
doc = fitz.open("file.pdf")
for page in doc:
text = page.getText()
print(text)
好吧,我也遇到了PyPDF2
相同的问题,所以我使用了另一个名为slate
的 python 库
安装库
pip install slate3k
然后使用下面的代码
import slate3k as slate with open(file.pdf, 'rb') as f: extracted_text = slate.PDF(f) print(extracted_text)
我使用 pdfminer 提取 pdf。
您可以参考示例代码。
#pip install pdfminer.six
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
def convert_pdf_to_txt(path):
'''Convert pdf content from a file path to text
:path the file path
'''
rsrcmgr = PDFResourceManager()
codec = 'utf-8'
laparams = LAParams()
with io.StringIO() as retstr:
with TextConverter(rsrcmgr, retstr, codec=codec,
laparams=laparams) as device:
with open(path, 'rb') as fp:
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
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)
return retstr.getvalue()
if __name__ == "__main__":
print(convert_pdf_to_txt('test.pdf'))
有关此盖子的更多信息。 你可以参考下面的链接
如果有任何问题,请检查并回复我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.