如何从 Python 3.7 中的 pdf 中提取文本

How to extract text from pdf in Python 3.7

我正在尝试使用 Python 从 PDF 文件中提取文本。我的主要目标是尝试创建一个程序来读取银行对帐单并提取其文本以更新 excel 文件以轻松记录每月支出。现在我只专注于从 pdf 文件中提取文本,但我不知道该怎么做。

目前将 PDF 文件中的文本提取为字符串的最佳和最简单的方法是什么?今天最好使用哪个库,我该怎么做?

我曾尝试使用 PyPDF2,但每次我尝试使用 extractText() 从任何页面中提取文本时,它 returns 都是空字符串。我已经尝试安装 textract 但出现错误,因为我认为我需要更多库。

from PyPDF2 import PdfReader

reader = PdfReader("January2019.pdf")
page = reader.pages[0]
print(page.extract_text())

本应打印页面内容时打印空字符串

PyPDF2 无法正确读取整个 pdf。您必须使用此代码。

    import pdftotext

    pdfFileObj = open("January2019.pdf", 'rb')


    pdf = pdftotext.PDF(pdfFileObj)

    # Iterate over all the pages
    for page in pdf:
        print(page)

使用 tika 对我有用!

from tika import parser

rawText = parser.from_file('January2019.pdf')

rawList = rawText['content'].splitlines()

这使得将银行对帐单中的每一行单独提取到列表中变得非常容易。

import pdftables_api
import os

c = pdftables_api.Client('MY-API-KEY')

file_path = "C:\Users\MyName\Documents\PDFTablesCode\"

for file in os.listdir(file_path):
    if file.endswith(".pdf"):
        c.xlsx(os.path.join(file_path,file), file+'.xlsx')

前往 https://pdftables.com 获取 API 密钥。

CSV,格式=csv

XML, 格式=xml

HTML,格式=html

XLSX,格式=xlsx-单,格式=xlsx-多

我试过很多方法都失败了,包括PyPDF2和Tika。我终于找到适合我的模块pdfplumber,你也可以试试。

希望对您有所帮助。

import pdfplumber
pdf = pdfplumber.open('pdffile.pdf')
page = pdf.pages[0]
text = page.extract_text()
print(text)
pdf.close()

尝试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

PyPDF2 从 pdf 中提取文本非常不可靠。正如 here 所指出的那样。 它说:

While PyPDF2 has .extractText(), which can be used on its page objects (not shown in this example), it does not work very well. Some PDFs will return text and some will return an empty string. When you want to extract text from a PDF, you should check out the PDFMiner project instead. PDFMiner is much more robust and was specifically designed for extracting text from PDFs.

  1. 您可以使用

    安装和使用 pdfminer

    pip install pdfminer

  2. 或者您可以使用另一个由 xpdfreader 命名的开源实用程序 pdftotext。页面上提供了使用该实用程序的说明。

您可以从 here 下载命令行工具 并且可以通过 subprocess 使用 pdftotext.exe 实用程序。给出了使用子进程的详细说明 here

这是Windows 10、Python 3.8

中的替代解决方案

示例测试 pdf:https://drive.google.com/file/d/1aUfQAlvq5hA9kz2c9CyJADiY3KpY3-Vn/view?usp=sharing

#pip install pdfminer.six
import io

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage


def convert_pdf_to_txt(path):
    '''Convert pdf content from a file path to text

    :path the file path
    '''
    rsrcmgr = PDFResourceManager()
    codec = 'utf-8'
    laparams = LAParams()

    with io.StringIO() as retstr:
        with TextConverter(rsrcmgr, retstr, codec=codec,
                           laparams=laparams) as device:
            with open(path, 'rb') as fp:
                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)

                return retstr.getvalue()


if __name__ == "__main__":
    print(convert_pdf_to_txt('C:\Path\To\Test_PDF.pdf'))

试试这个:

在终端执行命令:pip install PyPDF2

import PyPDF2

reader = PyPDF2.PdfReader("mypdf.pdf")
for page in reader.pages:
    print(page.extract_text())

如果您正在寻找一个维护的、更大的项目,请查看 PyMuPDF。使用 pip install pymupdf 安装它并像这样使用它:

import fitz

def get_text(filepath: str) -> str:
    with fitz.open(filepath) as doc:
        text = ""
        for page in doc:
            text += page.getText().strip()
        return text

我认为这段代码正是您要找的:

import requests, time, datetime, os, threading, sys, configparser
import glob
import pdfplumber

for filename in glob.glob("*.pdf"):
    pdf = pdfplumber.open(filename)
    OutputFile = filename.replace('.pdf','.txt')
    fx2=open(OutputFile, "a+")
    for i in range(0,10000,1):
        try:
            page = pdf.pages[i]
            text = page.extract_text()
            print(text)
            fx2.write(text)
        except Exception as e: 
            print(e)
    fx2.close()
    pdf.close()