在 Python3 textract 库中使用 tesseract

Using tesseract in Python3 textract library

我想从 PDF 文件中提取文本。我可以成功安装 tesseract(它在终端中工作)和 textract(遵循 this 指令)。

但是,当我运行代码时,我得到了一个错误。

text = textract.process(
    '/Users/Text/en.pdf',
    method='tesseract',
    language='eng',
)

错误是:

/usr/local/lib/python3.4/site-packages/textract-1.4.0-py3.4.egg/textract/parsers/pdf_parser.py in extract_tesseract(self, filename, **kwargs)
     62                 page_content = TesseractParser().extract(page_path, **kwargs)
     63                 contents.append(page_content)
---> 64             return ''.join(contents)
     65         finally:
     66             shutil.rmtree(temp_dir)

TypeError: sequence item 0: expected str instance, bytes found

我尝试了几次修改,但它们都不起作用,我得到了同样的错误。

  1. return b''.join(contents)
  2. return
  3. 之前插入contents = [str(item) for item in contents]
  4. return
  5. 之前插入contents = [item.decode("utf-8") for item in contents]

实际上,我在Japanese Whosebug (スタックオーバーフロー)中做了同样的问题并得到了解决方案。以下是我翻译的核心部分。 (谢谢,@mjy)。

注意:此修改至少适用于英语。

  1. 第 64 行 pdf_parser.py
    return ''.join(contents) 更改为

    return "".join(item.decode('utf-8') if isinstance(item, bytes) else item for item in contents)
    
  2. 但是,又出现了一个错误。

    NameError: name 'unicode' is not defined

  3. utils.py 的第 54 行中,将 if isinstance(text, unicode): (...cont...) 更改为

    if isinstance(text, str):
        return text