我正在尝试从PDF中提取文本,以便可以对其进行分析,但是当我尝试从页面中提取文本时,出现以下错误。
Traceback (most recent call last):
File "C:\Program Files (x86)\eclipse\plugins\org.python.pydev_2.7.4.2013051601\pysrc\pydevd_comm.py", line 765, in doIt
result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec)
File "C:\Program Files (x86)\eclipse\plugins\org.python.pydev_2.7.4.2013051601\pysrc\pydevd_vars.py", line 376, in evaluateExpression
result = eval(compiled, updated_globals, frame.f_locals)
File "<string>", line 1, in <module>
File "C:\Python33\lib\site-packages\pypdf2-1.9.0-py3.3.egg\PyPDF2\pdf.py", line 1701, in extractText
content = ContentStream(content, self.pdf)
File "C:\Python33\lib\site-packages\pypdf2-1.9.0-py3.3.egg\PyPDF2\pdf.py", line 1783, in __init__
stream = StringIO(stream.getData())
File "C:\Python33\lib\site-packages\pypdf2-1.9.0-py3.3.egg\PyPDF2\generic.py", line 801, in getData
decoded._data = filters.decodeStreamData(self)
File "C:\Python33\lib\site-packages\pypdf2-1.9.0-py3.3.egg\PyPDF2\filters.py", line 228, in decodeStreamData
data = ASCII85Decode.decode(data)
File "C:\Python33\lib\site-packages\pypdf2-1.9.0-py3.3.egg\PyPDF2\filters.py", line 170, in decode
data = [y for y in data if not (y in ' \n\r\t')]
File "C:\Python33\lib\site-packages\pypdf2-1.9.0-py3.3.egg\PyPDF2\filters.py", line 170, in <listcomp>
data = [y for y in data if not (y in ' \n\r\t')]
TypeError: 'in <string>' requires string as left operand, not int
相关代码节如下:
from PyPDF2 import PdfFileReader
for PDF_Entry in self.PDF_List:
Pdf_File = PdfFileReader(open(PDF_Entry, "rb"))
for pg_idx in range(0, Pdf_File.getNumPages()):
page_Content = Pdf_File.getPage(pg_idx).extractText()
for line in page_Content.split("\n"):
self.Analyse_Line(line)
将错误抛出在extractText()行。
最佳答案
可能值得尝试最新版本的PyPDF2,因为我写的是1.24。
如此说来,我发现extractText()功能非常脆弱。它适用于某些文档,而不适用于其他文档。查看一些未解决的问题:
https://github.com/mstamy2/PyPDF2/issues/180和https://github.com/mstamy2/PyPDF2/issues/168
我改用Poppler命令行实用程序pdftotext解决了该问题,将文档分类为图像还是文本,并获取了所有内容。对我来说一直非常稳定-我已经在成千上万的PDF文档上运行了它。以我的经验,它还可以毫不费力地从受保护/加密的PDF中提取文本。
例如(为Python 2编写):
def consult_pdftotext(filename):
'''
Runs pdftotext to extract text of pages 1..3.
Returns the count of characters received.
`filename`: Name of PDF file to be analyzed.
'''
print("Running pdftotext on file %s" % filename, file=sys.stderr)
# don't forget that final hyphen to say, write to stdout!!
cmd_args = [ "pdftotext", "-f", "1", "-l", "3", filename, "-" ]
pdf_pipe = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
std_out, std_err = pdf_pipe.communicate()
count = len(std_out)
return count
高温超导
关于python - pyPDF2中的extractText()函数抛出错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16877491/