-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract_pdf_text.py
More file actions
55 lines (39 loc) · 1.58 KB
/
extract_pdf_text.py
File metadata and controls
55 lines (39 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3
import os
import PyPDF2
from pathlib import Path
def extract_pdf_text(pdf_path, txt_path):
"""Extract text from PDF and save to TXT file"""
try:
with open(pdf_path, 'rb') as pdf_file:
pdf_reader = PyPDF2.PdfReader(pdf_file)
text_content = []
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
text_content.append(page.extract_text())
full_text = '\n'.join(text_content)
with open(txt_path, 'w', encoding='utf-8') as txt_file:
txt_file.write(full_text)
print(f"✓ Extracted {len(pdf_reader.pages)} pages from {pdf_path.name} -> {txt_path.name}")
return True
except Exception as e:
print(f"✗ Error extracting {pdf_path.name}: {str(e)}")
return False
def main():
books_dir = Path("books")
if not books_dir.exists():
print("Books directory not found!")
return
pdf_files = list(books_dir.glob("*.pdf"))
if not pdf_files:
print("No PDF files found in books directory!")
return
print(f"Found {len(pdf_files)} PDF files to process...")
success_count = 0
for pdf_file in pdf_files:
txt_file = pdf_file.with_suffix('.txt')
if extract_pdf_text(pdf_file, txt_file):
success_count += 1
print(f"\nCompleted: {success_count}/{len(pdf_files)} files successfully extracted")
if __name__ == "__main__":
main()