PDF提取中的空白和奇怪的单词解释

2024-04-30 07:04:51 发布

您现在位置:Python中文网/ 问答频道 /正文

使用下面的代码片段,我试图从thisPDF文件中提取文本数据。

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

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

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

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


Tags: 文件数据path代码text文本importget
3条回答

作为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)

不使用PyPdf2,使用Pdfminer库包,该包与下面的功能相同。我从this那里得到了代码,按照我的要求我对它进行了编辑,这段代码给了我一个文本文件,其中的单词之间有空白。我和anaconda和python 3.6一起工作。对于安装Python3.6的PdfMiner,可以使用这个link

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())

PDF文件没有可打印的空格字符,它只是将单词放置在需要的位置。您需要做额外的工作来计算空格,可能是假设多个字符的运行是单词,并在它们之间放置空格。

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

“fi”是一个排版连字,显示为单个字符。你可能会发现这也发生在“fl”、“ffi”和“ffl”上。您可以使用字符串替换用“fi”替换fi连字。

相关问题 更多 >