python - 尝试使用 pdfminer.6 提取文本时如何修复 'UnicodeDecodeError'?

标签 python pdf python-unicode pdfminer

使用通过pip install git+https://github.com/pdfminer/pdfminer.six.git安装的pdfminer(latest version from git)时遇到UnicodeEncodeError:

Traceback (most recent call last):
  File "pdfminer_sample3.py", line 34, in <module>
    print(convert_pdf_to_txt("samples/numbers-test-document.pdf"))
  File "pdfminer_sample3.py", line 27, in convert_pdf_to_txt
    text = retstr.getvalue()
  File "/usr/lib/python2.7/StringIO.py", line 271, in getvalue
    self.buf += ''.join(self.buflist)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

我该如何解决这个问题?

脚本

#!/usr/bin/env python

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from StringIO import StringIO
import codecs

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)

    fp = file(path, 'rb')
    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)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

print(convert_pdf_to_txt("samples/numbers-test-document.pdf"))

示例 pdf

https://www.dropbox.com/s/khjfr63o82fa5yn/numbers-test-document.pdf?dl=0

最佳答案

from StringIO import StringIO 替换为 from io import BytesIO

retstr = StringIO()替换为retstr = BytesIO()

关于python - 尝试使用 pdfminer.6 提取文本时如何修复 'UnicodeDecodeError'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45101658/

相关文章:

python - Coin Flip Streaks Challenge - Al Sweigart 用 python 自动化无聊的东西

python - 让 Django 接受带有无限参数的 url

php - 如何在TCPDF或FPDF中正确格式化?

php - 将html网页转换为pdf页面(用户将下载的pdf文件)

python - 使用 reportlab 在 PDF 文件中创建渐变填充

python - 在 Python 3 中加载 Python 2 .npy 文件

python - 如何使用 Python 将用户移动到不同的 OU

Python: '{:,}' .format() 为何有效?

Python 转义序列\N{name} 不按定义工作

python - 当前从解码字符串中删除 'surrogateescape' 个字符的习惯用法