PDF提取中的空格消失了,奇怪的单词解释



使用下面的代码片段,我尝试从这个PDF文件中提取文本数据。

import pyPdf
def get_text(path):
    # Load PDF into pyPDF
    pdf = pyPdf.PdfFileReader(file(path, "rb"))
    # Iterate pages
    content = ""
    for i in range(0, pdf.getNumPages()):
        content += pdf.getPage(i).extractText() + "n"  # Extract text from page and add to content
    # Collapse whitespace
    content = " ".join(content.replace(u"xa0", " ").strip().split())
    return content

但是,我获得的输出在大多数单词之间没有空格。这使得对文本执行自然语言处理变得困难(我的最终目标,在这里)。

此外,"手指"一词中的"fi"一直被解释为其他东西。这是相当有问题的,因为本文是关于自发的手指运动......

有谁知道为什么会发生这种情况?我什至不知道从哪里开始!

不使用 PyPdf2 使用 Pdfminer 库包,它具有与 bellow 相同的功能。我从中获得了代码,并按照我的意愿对其进行了编辑,该代码给了我一个文本文件,该文件在单词之间有空格。我使用 anaconda 和 python 3.6。对于安装Python 3.6的PdfMiner,您可以使用此链接。

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
class PdfConverter:
   def __init__(self, file_path):
       self.file_path = file_path
# convert pdf file to a string which has space among words 
   def convert_pdf_to_txt(self):
       rsrcmgr = PDFResourceManager()
       retstr = StringIO()
       codec = 'utf-8'  # 'utf16','utf-8'
       laparams = LAParams()
       device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
       fp = open(self.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)
       fp.close()
       device.close()
       str = retstr.getvalue()
       retstr.close()
       return str
# convert pdf file text to string and save as a text_pdf.txt file
   def save_convert_pdf_to_txt(self):
       content = self.convert_pdf_to_txt()
       txt_pdf = open('text_pdf.txt', 'wb')
       txt_pdf.write(content.encode('utf-8'))
       txt_pdf.close()
if __name__ == '__main__':
    pdfConverter = PdfConverter(file_path='sample.pdf')
    print(pdfConverter.convert_pdf_to_txt())

编辑:自从我写了这个答案以来,PyPDF2 改进了很多。我建议要么继续使用 PyPDF2,要么使用 pdfium。PyPDF2现在比pdftotext更好:-)

作为 PyPDF2 的替代方案,我建议pdftotext

#!/usr/bin/env python
"""Use pdftotext to extract text from PDFs."""
import pdftotext
with open("foobar.pdf") as f:
    pdf = pdftotext.PDF(f)
# Iterate over all the pages
for page in pdf:
    print(page)

您的PDF文件没有可打印的空格字符,它只是将单词放置在需要的位置。 你必须做额外的工作来找出空格,也许是通过假设多字符运行是单词,并在它们之间放置空格。

如果您可以在PDF阅读器中选择文本,并正确显示空格,那么至少您知道有足够的信息来重建文本。

"fi"是一个排版连字,显示为单个字符。 您可能会发现"fl","ffi"和"ffl"也发生这种情况。 您可以使用字符串替换来替换"fi"来代替连字。

PyPDF 不读取换行符。

所以使用 PyPDF4

使用

安装
pip install PyPDF4

并使用此代码作为示例

import PyPDF4
import re
import io
pdfFileObj = open(r'3134.pdf', 'rb')
pdfReader = PyPDF4.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(1)
pages_text = pageObj.extractText()
for line in pages_text.split('n'):
    #if re.match(r"^PDF", line):
    print(line)

我尝试在这里给出答案,但它对我不起作用。 以下适用于我的情况:

from pdf2image import convert_from_path
import pytesseract
images = convert_from_path("sample.pdf")
for i,image in enumerate(images,start=1):
    image.save(f"./images/page_{i}.jpg","JPEG")
print(pytesseract.image_to_string("./images/page_1.jpg"))

这里的想法是首先将PDF转换为图像,然后从中读取文本。此方法保留空格。

依赖关系:

  • conda install -c conda-forge tesseract
  • 康达安装 PDF2图像
  • 康达安装皮特塞拉特

我已经通过使用R解决了这个问题:

library(pdftools)
pdf_file <- "xxx/untitled.pdf"
text <- pdf_text(pdf_file)
cat(text[1])

PDFBox是一个非常好的工具,用于使用Java从PDF文件中提取文本。 文本提取是它的优势;如果您想修改/注释或查看PDF文件,其他工具可能会更好地为您服务。 它具有用于标识文件中空格的代码。

它还具有用于处理连字的代码,但是您需要在类路径上具有一定的国际化库才能正常工作 - Icu4j。

你可以从Python调用PDFBox文本提取器作为命令行程序,而无需编写任何Java代码。

最新更新