maintain consistency between lengths of paragraphs
%%
import re
import unidecode
from icecream import ic
def split_legal_paragraphs(text, min_length=100, max_length=1000, join_threshold=50):
"""
Split text into paragraphs, merging very short paragraphs with the next one
while maintaining size consistency and preserving meaning.
Args:
text (str): Input legal document text
min_length (int): Minimum paragraph length (characters)
max_length (int): Maximum paragraph length (characters)
join_threshold (int): Threshold for merging short paragraphs
Returns:
list: List of paragraphs
"""
# Split text into initial paragraphs based on double newlines or other delimiters
initial_paragraphs = re.split(r"\n\s*\n", unidecode.unidecode(text.lower().strip()))
# Remove empty paragraphs and strip whitespace
initial_paragraphs = [p.strip() for p in initial_paragraphs if p.strip()]
final_paragraphs = []
i = 0
while i < len(initial_paragraphs):
current_para = initial_paragraphs[i]
# If paragraph is too short, try to merge with next
if len(current_para) < join_threshold and i + 1 < len(initial_paragraphs):
next_para = initial_paragraphs[i + 1]
combined = current_para + " " + next_para
# Check if combined paragraph is within acceptable length
if len(combined) <= max_length:
current_para = combined
i += 2 # Skip the next paragraph since it was merged
else:
final_paragraphs.append(current_para)
i += 1
else:
# If paragraph is too long, attempt to split at sentence boundaries
if len(current_para) > max_length:
sentences = re.split(r"(?<!art)\. ", current_para)
temp_para = ""
for sentence in sentences:
if len(temp_para) + len(sentence) <= max_length:
temp_para += sentence + " "
else:
if temp_para:
final_paragraphs.append(temp_para.strip())
temp_para = sentence + " "
if temp_para:
final_paragraphs.append(temp_para.strip())
else:
final_paragraphs.append(current_para)
i += 1
# Final pass to ensure no paragraphs are below min_length
result = []
i = 0
while i < len(final_paragraphs):
current = final_paragraphs[i]
if len(current) < min_length and i + 1 < len(final_paragraphs):
next_para = final_paragraphs[i + 1]
combined = current + " " + next_para
if len(combined) <= max_length:
result.append(combined)
i += 2
else:
result.append(current)
i += 1
else:
result.append(current)
i += 1
return result
with open("input.txt", "r", encoding="utf-16-le") as f:
sample_text = f.read()
f.close()
paragraphs = split_legal_paragraphs(sample_text)
ic(len(paragraphs))
for idx, para in enumerate(paragraphs, 1):
print(f"Paragraph {idx}:")
print(para)
print(f"(Length: {len(para)} characters)")
print("-" * 50)