-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpaper_reader.py
More file actions
48 lines (43 loc) · 1.63 KB
/
Copy pathpaper_reader.py
File metadata and controls
48 lines (43 loc) · 1.63 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
import os
import PyPDF2
class PaperReader:
"""Reads and extracts text sections from local PDF files."""
def __init__(self, papers_dir="papers/first_50"):
self.papers_dir = papers_dir
def list_papers(self):
"""Return all PDF filenames sorted."""
try:
files = [f for f in os.listdir(self.papers_dir) if f.lower().endswith(".pdf")]
files.sort()
return files
except FileNotFoundError:
return []
def read_pdf(self, file_name):
"""Extracts text from a PDF file and returns plain text."""
text = ""
file_path = os.path.join(self.papers_dir, file_name)
try:
with open(file_path, "rb") as f:
reader = PyPDF2.PdfReader(f)
for page in reader.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
except Exception as e:
print(f"Error reading {file_name}: {e}")
return text
def extract_sections(self, text):
"""
Roughly split text into sections by searching for common section headers.
Returns a dict {SectionName: snippet}.
"""
sections = {}
lowered = text.lower()
headings = ["abstract", "introduction", "methods", "materials and methods",
"results", "discussion", "conclusion", "conclusions"]
for h in headings:
idx = lowered.find(h)
if idx != -1:
snippet = text[idx: idx + 2000]
sections[h.capitalize()] = snippet.strip()
return sections