如何在python中将整个pdf转换为文本

时间:2019-04-01 17:59:06

标签: python python-3.x

我必须将整个pdf转换为文本。我在很多地方都看到过将pdf转换为文本但特定页面的情况。

 from PyPDF2 import PdfFileReader
    import os
    def text_extractor(path):
        with open(os.path.join(path,file), 'rb') as f:
            pdf = PdfFileReader(f)
###Here i can specify page but i need to convert whole pdf without specifying pages###
            page = pdf.getPage(0)
            text = page.extractText()
            print(text)
    if __name__ == '__main__':
        path="C:\\Users\\AAAA\\Desktop\\BB"
        for file in os.listdir(path):
            if not file.endswith(".pdf"):
                continue
            text_extractor(path)

如何在不使用getpage()的情况下将整个pdf文件转换为文本?

6 个答案:

答案 0 :(得分:2)

如果您只需要文本,则可能要使用textract as this answer recommends获取完整文档。

如果要使用PyPDF2,则可以先获取页面数,然后在每个页面上进行迭代,例如:

 from PyPDF2 import PdfFileReader
    import os
    def text_extractor(path):
        with open(os.path.join(path,file), 'rb') as f:
            pdf = PdfFileReader(f)
###Here i can specify page but i need to convert whole pdf without specifying pages###
            text = ""
            for page_num in range(pdf.getNumPages()):
                page = pdf.getPage(page_num)
                text += page.extractText()
            print(text)
    if __name__ == '__main__':
        path="C:\\Users\\AAAA\\Desktop\\BB"
        for file in os.listdir(path):
            if not file.endswith(".pdf"):
                continue
            text_extractor(path)

尽管您可能想记住文本来自哪个页面,在这种情况下,您可以使用列表:

page_text = []
for page_num in range(pdf.getNumPages()): # For each page
    page = pdf.getPage(page_num) # Get that page's reference
    page_text.append(page.extractText()) # Add that page to our array
for page in page_text:
    print(page) # print each page

答案 1 :(得分:1)

您可以使用tika完成此任务,但是输出需要进行一些清理。

from tika import parser

parse_entire_pdf = parser.from_file('mypdf.pdf', xmlContent=True)
parse_entire_pdf = parse_entire_pdf['content']
print (parse_entire_pdf)

此答案使用PyPDF2和encode('utf-8')将每页的输出保持在一起。

from PyPDF2 import PdfFileReader

def pdf_text_extractor(path):
  with open(path, 'rb') as f:
  pdf = PdfFileReader(f)

  # Get total pdf page number.
  totalPageNumber = pdf.numPages

  currentPageNumber = 0

  while (currentPageNumber < totalPageNumber):
    page = pdf.getPage(currentPageNumber)

    text = page.extractText()
    # The encoding put each page on a single line.  
    # type is <class 'bytes'>
    print(text.encode('utf-8'))

    #################################
    # This outputs the text to a list,
    # but it doesn't keep paragraphs 
    # together 
    #################################
    # output = text.encode('utf-8')
    # split = str(output, 'utf-8').split('\n')
    # print (split)
    #################################

    # Process next page.
    currentPageNumber += 1

path = 'mypdf.pdf'
pdf_text_extractor(path)

答案 2 :(得分:1)

尝试pdfreader。您可以提取包含“ pdf markdown”的纯文本或解码文本:

from pdfreader import SimplePDFViewer, PageDoesNotExist

fd = open(you_pdf_file_name, "rb")
viewer = SimplePDFViewer(fd)

plain_text = ""
pdf_markdown = ""

try:
    while True:
        viewer.render()
        pdf_markdown += viewer.canvas.text_content
        plain_text += "".join(viewer.canvas.strings)
        viewer.next()
except PageDoesNotExist:
    pass

答案 3 :(得分:0)

PDF是一种面向页面的格式,因此您需要处理页面的概念。

什么使它变得更加困难,您无法保证能够提取的摘录文本按页面上显示的相同顺序提取:PDF允许说“将文本放在顶部的1英寸的4x3框中,左边距1”。然后我可以将下一组文本放在同一页上的其他位置。

您的extractText()函数仅按文档顺序而不是表示顺序获取提取的文本块。

众所周知,很难以常见的有意义的方式提取表...您将它们视为表,PDF将其视为放置在页面上的文本块,几乎没有关系,甚至没有关系。

仍然,getPage()和extractText()是很好的起点,如果您只是格式化页面,它们可能会正常工作。

答案 4 :(得分:0)

我发现了一种非常简单的方法。

您必须执行以下步骤:

  1. 安装PyPDF2 :如果使用Anaconda,请执行此步骤,搜索 Anaconda Prompt 并输入以下命令,您需要管理员权限才能执行此操作。

    pip install PyPDF2

  

如果您不使用Anaconda,则必须安装pip并放置其路径   到您的cmd或终端。

  1. Python代码:以下代码显示了如何非常轻松地转换pdf文件:

    import PyPDF2
    
    with open("pdf file path here",'rb') as file_obj:
    pdf_reader = PyPDF2.PdfFileReader(file_obj)
    raw = pdf_reader.getPage(0).extractText()
    
    print(raw)
    

答案 5 :(得分:0)

我只是使用pdftotext模块轻松完成此操作。

import pdftotext

# Load your PDF
with open("test.pdf", "rb") as f:
    pdf = pdftotext.PDF(f)

# creating a text file after iterating through all pages in the pdf
file = open("test.txt", "w")
for page in pdf:
    file.write(page)
file.close()

链接:https://github.com/manojitballav/pdf-text

相关问题