Как извлечь текст из PDF-файлов, включая все пробелыPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Как извлечь текст из PDF-файлов, включая все пробелы

Сообщение Anonymous »

Я пытаюсь создать код для извлечения текста из PDF-файлов и помещения его в базу данных. Для этого я использую Extract_text().
Однако по какой-то причине некоторые пробелы между словами исчезают (например, Australian Shiraz Challenge --> AustralianShirazChallenge). Как мне с этим справиться или какой альтернативный метод/встроенную функцию мне следует использовать вместо этого.
Кроме того, мне нужно иметь возможность чтобы скорректировать мой код чтобы иметь возможность извлекать определенные «столбцы» со слишком большими дополнительными трудностями.

Код: Выделить всё

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



Подробнее здесь: https://stackoverflow.com/questions/792 ... the-spaces
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»