[Python] How do extract text from PDFs including all the spaces

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    I'm being trying to create some code to extract text from PDFs and putting them into a database, I've been using extract_text() for this. However, for some reason some of the spaces between words are disappearing, (e.g. Australian Shiraz Challenge --> AustralianShirazChallenge) How do I deal with this or what alternative method/in built function should I use instead.

    Additionally, I need to be able to adjust my code to be able to extract specific "columns" with too much additional difficulty.


    import math
    import pdfplumber
    import fitz

    def find_word_coordinates(pdf_path, search_word):
    """
    Find the exact coordinates of a specific word in a PDF file.

    :param pdf_path: Path to the PDF file
    :param search_word: The word to search for
    :return: A dictionary with page numbers as keys and lists of coordinates as values
    """

    coordinates = {}

    # Open the PDF file
    with fitz.open(pdf_path) as doc:
    for page_number in range(len(doc)):
    page = doc[page_number]

    # Search for the word in the page text
    text_instances = page.search_for(search_word)

    if text_instances:
    # Store the coordinates for the page
    coordinates = [
    inst.x0
    for inst in text_instances
    ]

    return coordinates

    # Function to extract blurb using keywords from the extracted text
    def extract_column(pdf_path,x0,y0,x1,y1):
    with pdfplumber.open(pdf_path) as pdf:
    for page in pdf.pages:
    # Get the dimensions of the page
    width, height = page.width, page.height

    # Define the crop box for the right-hand side (e.g., the right half of the page)
    right_side = (x0, y0, x1, y1) # Coordinates: (x0, y0, x1, y1)


    # Crop the page to focus on the right side
    cropped_page = page.within_bbox(right_side)
    print(page.within_bbox(right_side))

    # Extract text from the cropped area
    text = cropped_page.extract_text()

    return text

    def extract_full_text(pdf_path):
    with pdfplumber.open(pdf_path) as pdf:
    for page in pdf.pages:
    width, height = page.width, page.height
    name=extract_column(pdf_path,width/4,0,width,height/6);
    top=extract_column(pdf_path,width/4,0,width,height/4.8);
    column1=extract_column(pdf_path,0,height/4.8,width/5,height);

    M=find_word_coordinates(pdf_path, "Winemaking");
    N=min(M, key=lambda x:abs(x-width/2));
    column2=extract_column(pdf_path,width/5,height/4.8,N-2,height);

    P=find_word_coordinates(pdf_path, "Winemaker");
    Q=min(P, key=lambda x:abs(x-width*.77));
    column3=extract_column(pdf_path,N-2,height/4.8,Q-2,height);



    column4=extract_column(pdf_path,Q-2,height/4.8,width,height);

    text=[name,top,column1,column2,column3,column4];
    return text

    Continue reading...

Compartilhe esta Página