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

blz*_*blz 9 python pdf unicode pypdf

使用下面的代码片段中,我试图从提取文本数据这个 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
Run Code Online (Sandbox Code Playgroud)

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

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

有人知道为什么会这样吗?我甚至不知道从哪里开始!

Has*_*hmi 12

不使用PyPdf2使用具有相同功能的Pdfminer库包,如下所示.我从这里得到了代码,因为我想编辑它,这段代码给了我一个文字文件,其中有单词之间的空格.我使用anaconda和python 3.6.对于安装PdfMiner for python 3.6,您可以使用此链接.

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())
Run Code Online (Sandbox Code Playgroud)


Ned*_*der 6

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

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

"fi"是一种印刷结扎线,显示为单个字符.您可能会发现"fl","ffi"和"ffl"也会发生这种情况.您可以使用字符串替换来替换"fi"来替换fi连字.

  • 究竟.空格和"fi"在从文本到PDF的翻译中丢失了,而且它们没有回来. (2认同)
  • @Ned Batchelder,感谢您的回复!您能否澄清“假设多字符运行是单词”是什么意思?其次,鉴于“ fi”是一种印刷连字,我该如何去识别PDF这类特殊字符并将其翻译成两个(或更多)单独的字符?换句话说,您能建议一种自动处理此类情况的方法吗? (2认同)

Mar*_*oma 6

作为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)
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,这应该是最受欢迎的答案.我也希望这是进行在线搜索时的第一个条目. (3认同)
  • @BFurtado 确保安装了依赖项“sudo apt-get update”,然后“sudo apt-get install build-essential libpoppler-cpp-dev pkg-config python-dev” (2认同)

小智 5

PyPDF 不读取换行符。

所以使用PyPDF4

安装它使用

pip install PyPDF4
Run Code Online (Sandbox Code Playgroud)

并使用此代码作为示例

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)
Run Code Online (Sandbox Code Playgroud)