-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
82 lines (53 loc) · 1.81 KB
/
Copy pathparser.py
File metadata and controls
82 lines (53 loc) · 1.81 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import re
import os
from docx import Document
heading_pattern = re.compile(
r'^\s*(episode|ep|chapter|ch)\s*\d+',
re.IGNORECASE
)
def count_words(paragraphs):
text = "\n".join(paragraphs)
return len(text.strip().split())
def parse_document(doc):
episodes = []
current = None
for para in doc.paragraphs:
text = para.text.strip()
if not text:
continue
if heading_pattern.match(text):
if current:
current["word_count"] = count_words(current["paragraphs"])
episodes.append(current)
current = {
"title": text,
"paragraphs": []
}
else:
if current:
current["paragraphs"].append(text)
if current:
current["word_count"] = count_words(current["paragraphs"])
episodes.append(current)
return episodes
def export_episodes(episodes, output_folder, start_episode):
os.makedirs(output_folder, exist_ok=True)
for i, ep in enumerate(episodes):
new_doc = Document()
original_title = ep["title"]
# Remove Episode number from original heading
title = re.sub(
r'^\s*(episode|ep|chapter|ch)\s*\d+\s*[:.\-]?\s*',
'',
original_title,
flags=re.IGNORECASE
).strip()
if title:
new_heading = f"Ep {start_episode + i} - {title}"
else:
new_heading = f"Ep {start_episode + i}"
new_doc.add_heading(new_heading, level=1)
for para in ep["paragraphs"]:
new_doc.add_paragraph(para)
filename = f"Ep {start_episode + i}.docx"
new_doc.save(os.path.join(output_folder, filename))