Parsowanie .pdf i konwersja na .txt

1

Witam
Chciałem wyciągnąć dane z pdfa

Moje próby:

import os
from PyPDF2 import PdfReader

directory = 'E:\CODE\pdf_attachments' # Podaj ścieżkę do katalogu


for filename in os.listdir(directory):
    if filename.endswith('.pdf'):
        pdf_file = open(os.path.join(directory, filename), 'rb')
        pdf_reader = PdfReader(pdf_file)
        txt_file = open(os.path.join(directory, filename[:-4] + '.txt'), 'w', encoding='utf-8')
        for page in range(len(pdf_reader.pages)):
            txt_file.write(pdf_reader.pages[page].extract_text())
        pdf_file.close()
        txt_file.close()

Dane są nieciekawie wyświetla i rozjeżdżają się

Za pomocą pandas jest lepiej ale nadal nie wygląda to ciekawie:

import os
import pandas as pd
from PyPDF2 import PdfReader

directory = 'E:\CODE\pdf_attachments' # Podaj ścieżkę do katalogu

for filename in os.listdir(directory):
    if filename.endswith('.pdf'):
        pdf_file = open(os.path.join(directory, filename), 'rb')
        pdf_reader = PdfReader(pdf_file)
        txt_file = open(os.path.join(directory, filename[:-4] + '.txt'), 'w', encoding='utf-8')
        for page in range(len(pdf_reader.pages)):
            txt_file.write(pdf_reader.pages[page].extract_text())
        pdf_file.close()
        txt_file.close()
        txt_file = open(os.path.join(directory, filename[:-4] + '.txt'), 'r', encoding='utf-8')
        lines = txt_file.readlines()
        df = pd.DataFrame(lines)
        print(df.style.set_properties(**{'white-space': 'pre-wrap'}))


        print(df)
        txt_file.close()

Znalazłem jakiś lib camelot:

import camelot

tables = camelot.read_pdf('E:\CODE\pdf_attachments\example.pdf')

tables


tables.export('foo.csv', f='csv', compress=True) # json, excel, html, markdown, sqlite

tables[0]


tables[0].parsing_report
{
    'accuracy': 99.02,
    'whitespace': 12.24,
    'order': 1,
    'page': 1
}

tables[0].to_csv('foo.csv') # to_json, to_excel, to_html, to_markdown, to_sqlite

tables[0].df # get a pandas DataFrame!
print(tables)

I dostaje:

Traceback (most recent call last):
  File "e:\CODE\pdf-txt-v6.py", line 3, in <module>
    tables = camelot.read_pdf('E:\CODE\pdf_attachments\example.pdf')
             ^^^^^^^^^^^^^^^^
AttributeError: module 'camelot' has no attribute 'read_pdf'

Proszę o pomoc

2

Co do, camelot błąd jaki jest każdy widzi, sprawdź w dokumentacji. A co do bibliotek, używałem tego: https://textract.readthedocs.io/en/stable/python_package.html i śmigało ładnie.

2
lion137 napisał(a):

Co do, camelot błąd jaki jest każdy widzi, sprawdź w dokumentacji

dobre, tylko że w dokumentacji też jest taka linijka:

Ale nie bądźmy takimi ludzmi co wierzą dokumentacji. Przecież też może kłamać. Spójrzmy do kodu https://github.com/camelot-dev/camelot/blob/master/camelot/io.py

@Tommuuu: Może nie ten camelot dołączyłeś? albo jakąś starą wersję?

2

PyPDF2 wydaje się działać świetnie u mnie na prostym pliku:
https://africau.edu/images/default/sample.pdf

Mój kodzik (korzystając z okazji pozdrawiam Mamę, Tatę i ChatGPT):

import PyPDF2

# Open the PDF file
pdf_file = open('example.pdf', 'rb')

# Create a PDF reader object
pdf_reader = PyPDF2.PdfReader(pdf_file)

# Open a TXT file for writing
txt_file = open('example.txt', 'w')

# Iterate through all the pages in the PDF
for i in range(0, len(pdf_reader.pages)):
    # Extract the text from the current page
    page =  pdf_reader.pages[i]
    txt = page.extract_text()

    # Write the text to the TXT file
    txt_file.write(txt)

# Close the PDF and TXT files
pdf_file.close()
txt_file.close()
2

@Tommuuu: Tak jak słusznie pisze @KamilAdam sprawdź to, importujesz moduł, dalej, module.__version__, dir(module) i wiesz wszystko:)

1 użytkowników online, w tym zalogowanych: 0, gości: 1