也许您尝试阅读的 PDF 文件的编码尚不被 pdfMiner 支持。
上个月我遇到了类似的问题,最后通过使用名为“pdfBox”的java库并从python调用它来解决它。pdfBox 库支持我需要的编码,并且工作起来就像一个魅力!
首先,我从官方网站下载了 pdfbox
,然后从我的代码中引用了 .jar 文件的路径。
这是我使用的代码的简化版本(未经测试,但基于我的原始测试代码)。您将需要 subprocess32,您可以通过调用安装它pip install subprocess32
import subprocess32 as subprocess
import os
import tempfile
def extractPdf(file_path, pdfboxPath, timeout=30, encoding='UTF-8'):
#tempfile = temp_file(data, suffix='.pdf')
try:
command_args = ['java', '-jar', os.path.expanduser(pdfboxPath), 'ExtractText', '-console', '-encoding', encoding, file_path]
status, stdout, stderr = external_process(command_args, timeout=timeout)
except subprocess.TimeoutExpired:
raise RunnableError('PDFBox timed out while processing document')
finally:
pass#os.remove(tempfile)
if status != 0:
raise RunnableError('PDFBox returned error status code {0}.\nPossible error:\n{1}'.format(status, stderr))
# We can use result from PDFBox directly, no manipulation needed
pdf_plain_text = stdout
return pdf_plain_text
def external_process(process_args, input_data='', timeout=None):
process = subprocess.Popen(process_args,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
(stdout, stderr) = process.communicate(input_data, timeout)
except subprocess.TimeoutExpired as e:
# cleanup process
# see https://docs.python.org/3.3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate
process.kill()
process.communicate()
raise e
exit_status = process.returncode
return (exit_status, stdout, stderr)
def temp_file(data, suffix=''):
handle, file_path = tempfile.mkstemp(suffix=suffix)
f = os.fdopen(handle, 'w')
f.write(data)
f.close()
return file_path
if __name__ == '__main__':
text = extractPdf(filename, 'pdfbox-app-2.0.3.jar')
` 此代码并非完全由我编写。我遵循了其他堆栈溢出答案的建议,但那是一个月前,所以我失去了原始来源。如果有人找到我得到这段代码的原始帖子,请告诉我,这样我就可以为他们的代码给予他们应得的荣誉。