def extract_title(doc):
for para in doc.paragraphs:
if para.text.strip():
return para.text.strip()
return "Blank or No Title"
Extract summary
def extract_file_summary(doc, max_lines=5):
lines = []
for para in doc.paragraphs:
line = para.text.strip()
if line:
lines.append(line)
if len(lines) >= max_lines:
break
return " ".join(lines) if lines else "No content in document."
Extract present/missing schema-based sections
def analyze_structure(doc):
section_map = {key: False for key in expected_sections_with_titles}
for para in doc.paragraphs:
text = para.text.strip().upper()
for section in section_map:
if section in text:
section_map[section] = True
present = [f"{k} {expected_sections_with_titles[k]}" for k, v in section_map.items() if v]
missing = [f"{k} {expected_sections_with_titles[k]}" for k, v in section_map.items() if not v]
return present, missing
def extract_unexpected_headings(doc):
unexpected = []
for para in doc.paragraphs:
line = para.text.strip()
if not line:
continue
if (line.upper().startswith("PART-") or line.isupper()):
section_key = line.split()[0].upper()
if section_key not in expected_sections_with_titles:
unexpected.append(line)
return list(set(unexpected))
Process a single file
def process_file(file_path):
try:
doc = Document(file_path)
if not doc.paragraphs or all(not p.text.strip() for p in doc.paragraphs):
return "Blank or No Title", [], [], "Blank file.", []
title = extract_title(doc)
present, missing = analyze_structure(doc)
summary = extract_file_summary(doc)
unexpected = extract_unexpected_headings(doc)
return title, present, missing, summary, unexpected
except Exception as e:
return f"Error: {str(e)}", [], [], f"Error occurred: {str(e)}", []
def extract_title(doc):
for para in doc.paragraphs:
if para.text.strip():
return para.text.strip()
return "Blank or No Title"
Extract brief summary (first few non-empty lines)
def extract_file_summary(doc, max_lines=5):
lines = []
for para in doc.paragraphs:
line = para.text.strip()
if line:
lines.append(line)
if len(lines) >= max_lines:
break
return " ".join(lines) if lines else "No content in document."
Use regex to analyze which schema sections are present
def analyze_structure(doc):
section_map = {key: False for key in expected_sections_with_titles}
for para in doc.paragraphs:
text = para.text.strip()
for key, pattern in section_patterns.items():
if pattern.search(text):
section_map[key] = True
present = [f"{k} {expected_sections_with_titles[k]}" for k, v in section_map.items() if v]
missing = [f"{k} {expected_sections_with_titles[k]}" for k, v in section_map.items() if not v]
return present, missing
Detect headings not in schema, using uppercase or 'PART' keywords
def extract_unexpected_headings(doc):
unexpected = []
for para in doc.paragraphs:
line = para.text.strip()
if not line:
continue
if re.match(r"PART[- ]?[A-Z0-9()]+", line.upper()) or line.isupper():
matched = any(pattern.search(line) for pattern in section_patterns.values())
if not matched:
unexpected.append(line)
return list(set(unexpected))
Process one Word document
def process_file(file_path):
try:
doc = Document(file_path)
if not doc.paragraphs or all(not p.text.strip() for p in doc.paragraphs):
return "Blank or No Title", [], [], "Blank file.", []
title = extract_title(doc)
present, missing = analyze_structure(doc)
summary = extract_file_summary(doc)
unexpected = extract_unexpected_headings(doc)
return title, present, missing, summary, unexpected
except Exception as e:
return f"Error: {str(e)}", [], [], f"Error occurred: {str(e)}", []
Option #2's pattern definitions are more explicit and easier to modify if you need to adjust what counts as a section
Recommendations for Large-Scale Processing
For processing 2,500 files, I would recommend:
Use Option #2 as your base code
Add these improvements:
python
# Add progress tracking
import tqdm
# In process_all_folders, wrap the file processing loop with:
for i, file in enumerate(tqdm(files, desc=f"Processing {folder_name}")):
# existing code
Consider parallel processing for even better performance:
python
from multiprocessing import Pool
def process_folder(folder_path):
# Process a single folder
pass
def process_all_folders(base_path, output_excel_path):
folders = [f for f in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, f))]
with Pool() as pool:
results = list(tqdm(pool.imap(process_folder, folders), total=len(folders)))
# Combine results and save to Excel
Add memory management for large batches:
python
import gc
# After processing each batch of files
gc.collect()
The regex-based approach in Option #2 will give you more accurate results with less manual intervention needed for edge cases, making it the better choice for large-scale document processing.