Làm cách nào để trích xuất PDF thành văn bản Python?

Tiết lộ. Bài đăng này có thể chứa các liên kết liên kết, nghĩa là khi bạn nhấp vào liên kết và mua hàng, chúng tôi sẽ nhận được hoa hồng

Vào thời điểm này, các công ty quy mô vừa và lớn có lượng lớn tài liệu PDF được sử dụng hàng ngày. Trong số đó có hóa đơn, biên lai, tài liệu, báo cáo, v.v.

Trong hướng dẫn này, bạn sẽ học cách trích xuất văn bản từ tài liệu PDF bằng Python bằng thư viện PyMuPDF

Hướng dẫn này giải quyết vấn đề khi văn bản không được quét, tôi. e. , không phải hình ảnh trong PDF. Nếu bạn muốn trích xuất văn bản từ hình ảnh trong tài liệu PDF, hướng dẫn này là dành cho bạn

Để bắt đầu, chúng ta cần cài đặt PyMuPDF

$ pip install PyMuPDF==1.18.9

Mở một tệp Python mới và hãy nhập các thư viện

import fitz
import argparse
import sys
import os
from pprint import pprint

PyMuPDF có tên là

import fitz
import argparse
import sys
import os
from pprint import pprint
0 khi nhập bằng Python, vì vậy hãy ghi nhớ điều đó

Vì chúng ta sẽ tạo một tập lệnh Python để trích xuất văn bản từ tài liệu PDF, nên chúng ta phải sử dụng mô-đun argparse để phân tích các tham số đã truyền trong dòng lệnh. Hàm sau phân tích cú pháp các đối số và thực hiện một số xử lý

def get_arguments[]:
    parser = argparse.ArgumentParser[
        description="A Python script to extract text from PDF documents."]
    parser.add_argument["file", help="Input PDF file"]
    parser.add_argument["-p", "--pages", nargs="*", type=int,
                        help="The pages to extract, default is all"]
    parser.add_argument["-o", "--output-file", default=sys.stdout,
                        help="Output file to write text. default is standard output"]
    parser.add_argument["-b", "--by-page", action="store_true",
                        help="Whether to output text by page. If not specified, all text is joined and will be written together"]
    # parse the arguments from the command-line
    args = parser.parse_args[]

    input_file = args.file
    pages = args.pages
    by_page = args.by_page
    output_file = args.output_file
    # print the arguments, just for logging purposes
    pprint[vars[args]]
    # load the pdf file
    pdf = fitz.open[input_file]
    if not pages:
        # if pages is not set, default is all pages of the input PDF document
        pages = list[range[pdf.pageCount]]
    # we make our dictionary that maps each pdf page to its corresponding file
    # based on passed arguments
    if by_page:
        if output_file is not sys.stdout:
            # if by_page and output_file are set, open all those files
            file_name, ext = os.path.splitext[output_file]
            output_files = { pn: open[f"{file_name}-{pn}{ext}", "w"] for pn in pages }
        else:
            # if output file is standard output, do not open
            output_files = { pn: output_file for pn in pages }
    else:
        if output_file is not sys.stdout:
            # a single file, open it
            output_file = open[output_file, "w"]
            output_files = { pn: output_file for pn in pages }
        else:
            # if output file is standard output, do not open
            output_files = { pn: output_file for pn in pages }

    # return the parsed and processed arguments
    return {
        "pdf": pdf,
        "output_files": output_files,
        "pages": pages,
    }

Đầu tiên, chúng tôi đã tạo trình phân tích cú pháp của mình bằng cách sử dụng

import fitz
import argparse
import sys
import os
from pprint import pprint
1Và thêm các tham số sau

  • import fitz
    import argparse
    import sys
    import os
    from pprint import pprint
    2. Tài liệu PDF đầu vào để trích xuất văn bản từ
  • import fitz
    import argparse
    import sys
    import os
    from pprint import pprint
    3 hoặc
    import fitz
    import argparse
    import sys
    import os
    from pprint import pprint
    4. Chỉ số trang cần giải nén, bắt đầu từ 0, nếu bạn không chỉ định thì mặc định sẽ là tất cả các trang
  • import fitz
    import argparse
    import sys
    import os
    from pprint import pprint
    5 hoặc
    import fitz
    import argparse
    import sys
    import os
    from pprint import pprint
    6. Tệp văn bản đầu ra để viết văn bản trích xuất. Nếu bạn không chỉ định, nội dung sẽ được in ở đầu ra tiêu chuẩn [i. e. , trong bảng điều khiển]
  • import fitz
    import argparse
    import sys
    import os
    from pprint import pprint
    7 hoặc
    import fitz
    import argparse
    import sys
    import os
    from pprint import pprint
    8. Đây là một boolean cho biết có xuất văn bản theo trang hay không. Nếu không được chỉ định, tất cả văn bản sẽ được nối trong một tệp duy nhất [khi chỉ định
    import fitz
    import argparse
    import sys
    import os
    from pprint import pprint
    5]

Thứ hai, chúng tôi mở

def get_arguments[]:
    parser = argparse.ArgumentParser[
        description="A Python script to extract text from PDF documents."]
    parser.add_argument["file", help="Input PDF file"]
    parser.add_argument["-p", "--pages", nargs="*", type=int,
                        help="The pages to extract, default is all"]
    parser.add_argument["-o", "--output-file", default=sys.stdout,
                        help="Output file to write text. default is standard output"]
    parser.add_argument["-b", "--by-page", action="store_true",
                        help="Whether to output text by page. If not specified, all text is joined and will be written together"]
    # parse the arguments from the command-line
    args = parser.parse_args[]

    input_file = args.file
    pages = args.pages
    by_page = args.by_page
    output_file = args.output_file
    # print the arguments, just for logging purposes
    pprint[vars[args]]
    # load the pdf file
    pdf = fitz.open[input_file]
    if not pages:
        # if pages is not set, default is all pages of the input PDF document
        pages = list[range[pdf.pageCount]]
    # we make our dictionary that maps each pdf page to its corresponding file
    # based on passed arguments
    if by_page:
        if output_file is not sys.stdout:
            # if by_page and output_file are set, open all those files
            file_name, ext = os.path.splitext[output_file]
            output_files = { pn: open[f"{file_name}-{pn}{ext}", "w"] for pn in pages }
        else:
            # if output file is standard output, do not open
            output_files = { pn: output_file for pn in pages }
    else:
        if output_file is not sys.stdout:
            # a single file, open it
            output_file = open[output_file, "w"]
            output_files = { pn: output_file for pn in pages }
        else:
            # if output file is standard output, do not open
            output_files = { pn: output_file for pn in pages }

    # return the parsed and processed arguments
    return {
        "pdf": pdf,
        "output_files": output_files,
        "pages": pages,
    }
0 để viết vào nếu
import fitz
import argparse
import sys
import os
from pprint import pprint
7 được chỉ định. Nếu không, một tệp sẽ nằm trong từ điển
def get_arguments[]:
    parser = argparse.ArgumentParser[
        description="A Python script to extract text from PDF documents."]
    parser.add_argument["file", help="Input PDF file"]
    parser.add_argument["-p", "--pages", nargs="*", type=int,
                        help="The pages to extract, default is all"]
    parser.add_argument["-o", "--output-file", default=sys.stdout,
                        help="Output file to write text. default is standard output"]
    parser.add_argument["-b", "--by-page", action="store_true",
                        help="Whether to output text by page. If not specified, all text is joined and will be written together"]
    # parse the arguments from the command-line
    args = parser.parse_args[]

    input_file = args.file
    pages = args.pages
    by_page = args.by_page
    output_file = args.output_file
    # print the arguments, just for logging purposes
    pprint[vars[args]]
    # load the pdf file
    pdf = fitz.open[input_file]
    if not pages:
        # if pages is not set, default is all pages of the input PDF document
        pages = list[range[pdf.pageCount]]
    # we make our dictionary that maps each pdf page to its corresponding file
    # based on passed arguments
    if by_page:
        if output_file is not sys.stdout:
            # if by_page and output_file are set, open all those files
            file_name, ext = os.path.splitext[output_file]
            output_files = { pn: open[f"{file_name}-{pn}{ext}", "w"] for pn in pages }
        else:
            # if output file is standard output, do not open
            output_files = { pn: output_file for pn in pages }
    else:
        if output_file is not sys.stdout:
            # a single file, open it
            output_file = open[output_file, "w"]
            output_files = { pn: output_file for pn in pages }
        else:
            # if output file is standard output, do not open
            output_files = { pn: output_file for pn in pages }

    # return the parsed and processed arguments
    return {
        "pdf": pdf,
        "output_files": output_files,
        "pages": pages,
    }
0

Cuối cùng, chúng tôi trả về các biến cần thiết. Tài liệu PDF, tệp đầu ra và danh sách số trang

Tiếp theo, hãy tạo một hàm chấp nhận các tham số trên và trích xuất văn bản từ tài liệu PDF tương ứng

def extract_text[**kwargs]:
    # extract the arguments
    pdf          = kwargs.get["pdf"]
    output_files = kwargs.get["output_files"]
    pages        = kwargs.get["pages"]
    # iterate over pages
    for pg in range[pdf.pageCount]:
        if pg in pages:
            # get the page object
            page = pdf[pg]
            # extract the text of that page and split by new lines '\n'
            page_lines = page.get_text[].splitlines[]
            # get the output file
            file = output_files[pg]
            # get the number of lines
            n_lines = len[page_lines]
            for line in page_lines:
                # remove any whitespaces in the end & beginning of the line
                line = line.strip[]
                # print the line to the file/stdout
                print[line, file=file]
            print[f"[*] Wrote {n_lines} lines in page {pg}"]    
    # close the files
    for pn, f in output_files.items[]:
        if f is not sys.stdout:
            f.close[]

Chúng tôi lặp đi lặp lại trên các trang; . Cuối cùng, chúng tôi đóng các tập tin

Hãy tập hợp mọi thứ lại với nhau và chạy các chức năng

if __name__ == "__main__":
    # get the arguments
    kwargs = get_arguments[]
    # extract text from the pdf document
    extract_text[**kwargs]

Tuyệt vời, hãy thử trích xuất văn bản từ tất cả các trang của tệp này và ghi từng trang vào một tệp văn bản

$ python extract_text_from_pdf.py bert-paper.pdf -o text.txt -b

đầu ra

{'by_page': True,
 'file': 'bert-paper.pdf', 
 'output_file': 'text.txt',
 'pages': None}
[*] Wrote 97 lines in page 0
[*] Wrote 108 lines in page 1
[*] Wrote 136 lines in page 2
[*] Wrote 107 lines in page 3
[*] Wrote 133 lines in page 4
[*] Wrote 158 lines in page 5
[*] Wrote 163 lines in page 6
[*] Wrote 128 lines in page 7
[*] Wrote 158 lines in page 8
[*] Wrote 116 lines in page 9
[*] Wrote 124 lines in page 10
[*] Wrote 115 lines in page 11
[*] Wrote 135 lines in page 12
[*] Wrote 111 lines in page 13
[*] Wrote 153 lines in page 14
[*] Wrote 127 lines in page 15

Nó hoạt động hoàn hảo. Đây là các tập tin đầu ra

Bây giờ hãy chỉ định các trang 0, 1, 2, 14 và 15

$ python extract_text_from_pdf.py bert-paper.pdf -o text.txt -b -p 0 1 2 14 15   
{'by_page': True,
 'file': 'bert-paper.pdf',
 'output_file': 'text.txt',
 'pages': [0, 1, 2, 14, 15]}
[*] Wrote 97 lines in page 0
[*] Wrote 108 lines in page 1
[*] Wrote 136 lines in page 2
[*] Wrote 153 lines in page 14
[*] Wrote 127 lines in page 15

Chúng tôi cũng có thể in trong bảng điều khiển thay vì lưu nó vào tệp bằng cách không đặt tùy chọn

import fitz
import argparse
import sys
import os
from pprint import pprint
5

$ python extract_text_from_pdf.py bert-paper.pdf -p 0
{'by_page': False,
 'file': 'bert-paper.pdf',
 'output_file': ,
 'pages': [0]}
BERT: Pre-training of Deep Bidirectional Transformers for
Language Understanding
Jacob Devlin
Ming-Wei Chang
Kenton Lee
Kristina Toutanova
Google AI Language
{jacobdevlin,mingweichang,kentonl,kristout}@google.com
Abstract
We introduce a new language representa-
tion model called BERT, which stands for
Bidirectional Encoder Representations from
...

[*] Wrote 97 lines in page 0

Hoặc lưu tất cả văn bản của tài liệu PDF vào một tệp văn bản

$ python extract_text_from_pdf.py bert-paper.pdf -o all-text.txt

Tệp đầu ra sẽ xuất hiện trong thư mục hiện tại

Phần kết luận

Được rồi, đó là nó cho hướng dẫn này. Như đã đề cập trước đó, bạn luôn có thể trích xuất văn bản từ hướng dẫn tài liệu PDF được quét nếu tài liệu của bạn được quét [i. e. , dưới dạng hình ảnh và không thể được chọn trong trình đọc PDF của bạn]

Ngoài ra, bạn có thể sắp xếp lại và đánh dấu văn bản trong tệp PDF của mình. Dưới đây là một số hướng dẫn PDF liên quan khác

Hoặc bạn có thể khám phá tất cả chúng tại đây

Kiểm tra mã hoàn chỉnh ở đây

Cuối cùng, nếu bạn là người mới bắt đầu và muốn học Python, tôi khuyên bạn nên tham gia khóa học Python For Everyone Coursera, trong đó bạn sẽ học được nhiều điều về Python. Bạn cũng có thể xem trang tài nguyên và khóa học của chúng tôi để xem các tài nguyên Python mà tôi đề xuất về các chủ đề khác nhau

Cách dễ nhất để trích xuất văn bản từ PDF bằng Python là gì?

Công cụ chúng tôi đang sử dụng trong hướng dẫn này là PDF Plumber, một gói mã nguồn mở của python, rất tuyệt vời, đơn giản và mạnh mẽ. .
Nhập mô-đun của bạn. pip cài đặt pdfplumber -qimport pdfplumber. .
open['đường dẫn/đến/thư mục'].
trang[ ].
trích_văn[]

Làm cách nào chúng tôi có thể trích xuất văn bản cụ thể từ PDF bằng Python?

Đối tượng trang có chức năng extractText[] để trích xuất văn bản từ trang pdf.

Làm cách nào để trích xuất văn bản từ hình ảnh PDF bằng Python?

Python trích xuất văn bản từ hình ảnh hoặc pdf. .
mở tệp PDF bằng cây đũa phép / imagemagick
chuyển đổi PDF sang hình ảnh
đọc từng hình ảnh một và trích xuất văn bản bằng pytesseract/tesseract-ocr

Chủ Đề