scripts / mergetxts.py
ElijahSturges's picture
Upload 3 files
f434b4c verified
Raw History Blame Contribute Delete
2.15 kB
from pathlib import Path
import re
# Folder containing the OCR subfolders
input_dir = Path(
"/Users/productivity/Downloads/Approaching_Religion/OCR"
)
# Folder where the master documents will be saved
output_dir = Path(
"/Users/productivity/Downloads/Approaching_Religion/MasterDocuments"
)
output_dir.mkdir(parents=True, exist_ok=True)
# Find each subfolder corresponding to an original PDF
subfolders = sorted(
folder for folder in input_dir.iterdir()
if folder.is_dir()
)
successful = 0
failed = []
print(f"Found {len(subfolders)} OCR subfolders.\n")
for index, folder in enumerate(subfolders, start=1):
# Find all page-level text files
txt_files = list(folder.glob("*.txt"))
# Sort by page number, rather than ordinary alphabetical order
def page_number(path):
match = re.search(r"_page_(\d+)$", path.stem)
return int(match.group(1)) if match else float("inf")
txt_files.sort(key=page_number)
if not txt_files:
print(f"WARNING: No TXT files found in {folder.name}")
failed.append(folder.name)
continue
master_path = output_dir / f"{folder.name}.txt"
try:
with master_path.open("w", encoding="utf-8") as master:
for txt_file in txt_files:
master.write(
f"\n\n{'=' * 30}\n"
f"PAGE: {txt_file.stem}\n"
f"{'=' * 30}\n\n"
)
master.write(
txt_file.read_text(
encoding="utf-8",
errors="replace"
)
)
successful += 1
print(
f"[{index}/{len(subfolders)}] "
f"Created {master_path.name} "
f"from {len(txt_files)} pages"
)
except OSError as exc:
print(f"ERROR: {folder.name}: {exc}")
failed.append(folder.name)
print("\nMaster document creation complete.")
print(f"Created: {successful}")
print(f"Failed or empty: {len(failed)}")
if failed:
print("\nFolders requiring attention:")
for name in failed:
print(f" - {name}")