我正在尝试使用Python
提取包含在this文件中的文本。
我使用的是PyPDF2模块,并具有以下脚本:
import PyPDF2
pdf_file = open('sample.pdf')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content
当我运行代码时,我得到以下输出,它与PDF文档中包含的输出不同:
!"#$%#$%&%$&'()*%+,-%./01'*23%4
5'%1$#26%3/%7/))/8%&)/26%8#3"%3"*%313/9#&)
%
如何提取PDF文档中的文本?
发布于 2016-01-20 12:00:40
看看这段代码:
import PyPDF2
pdf_file = open('sample.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content.encode('utf-8')
输出为:
!"#$%#$%&%$&'()*%+,-%./01'*23%4
5'%1$#26%3/%7/))/8%&)/26%8#3"%3"*%313/9#&)
%
使用相同的代码从201308FCR.pdf .The输出中读取pdf是正常的。
它的documentation解释了原因:
def extractText(self):
"""
Locate all text drawing commands, in the order they are provided in the
content stream, and extract the text. This works well for some PDF
files, but poorly for others, depending on the generator used. This will
be refined in the future. Do not rely on the order of text coming out of
this function, as it will change if this function is made more
sophisticated.
:return: a unicode string object.
"""
发布于 2018-03-14 04:30:58
在尝试了textract (它似乎有太多的依赖项)和pypdf2 (它不能从我测试的pdf中提取文本)和tika (太慢)之后,我最终使用了xpdf中的pdftotext
(正如在另一个答案中已经建议的那样),并直接从python中调用了二进制文件(您可能需要将路径调整为pdftotext):
import os, subprocess
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
args = ["/usr/local/bin/pdftotext",
'-enc',
'UTF-8',
"{}/my-pdf.pdf".format(SCRIPT_DIR),
'-']
res = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = res.stdout.decode('utf-8')
pdftotext的功能基本相同,但假设pdftotext在/usr/local/bin中,而我在AWS lambda中使用它,并希望在当前目录中使用它。
顺便说一下:为了在lambda上使用它,你需要把二进制文件和对libstdc++.so
的依赖放到你的lambda函数中。我个人需要编译xpdf。因为这样做的说明会毁了这个答案,所以我把它们放在on my personal blog上。
发布于 2016-01-18 16:42:47
您可能希望使用经过时间验证的xPDF和派生工具来提取文本,因为pyPDF2似乎仍然具有文本提取的various issues。
长期的答案是,有很多变化的文本是如何在PDF中编码,这可能需要解码的PDF字符串本身,然后可能需要映射与CMAP,然后可能需要分析之间的单词和字母的距离等。
如果PDF是损坏的(即显示正确的文本,但当复制它时产生垃圾),你真的需要提取文本,那么你可能要考虑转换PDF为图像(使用ImageMagik),然后使用Tesseract从图像中使用光学字符识别获取文本。
https://stackoverflow.com/questions/34837707
复制相似问题