프로그래밍/Python

[Python] PDF Text 추출하기

ordinary_daisy 2024. 8. 22. 12:18

개요

  • pdf 파일에 쓰여있는 text 들을 다른 파일이나 db로 넣어야 할 때, text를 간단히 추출하고 싶어서 찾아보다 정리하게 됨
  • 사실 pdf를 chatGPT에 첨부해 분석해달라고 하면 너무 편하겠지만, 보안성이 조금이라도 있다면 chatGPT에 부탁하기 꺼려짐
  • 아래 코드를 돌리면 간단하게 text 추출이 가능함

python 코드

import PyPDF2

# Path to the uploaded PDF file
pdf_path = './test.pdf'

# Function to extract text from each page of the PDF
def extract_text_from_pdf(pdf_path):
    with open(pdf_path, 'rb') as file:
        reader = PyPDF2.PdfReader(file)
        text = ""
        for page_num in range(len(reader.pages)):
            text += reader.pages[page_num].extract_text()
    return text

# Extract the text from the PDF
pdf_text = extract_text_from_pdf(pdf_path)
print(pdf_text)