Below is the tiny tweak you need:
just add a final .strip() after the whitespace-collapse regex.
Everything else stays exactly as in the previous version, so the <div> logic is untouched (it still produces “\ncontent\n”), but now all leading and trailing whitespace—including new-lines—is trimmed from the very end result.
import os
import re
from bs4 import BeautifulSoup, NavigableString
# Input and output directories
input_dir = 'justify'
output_dir = 'clean'
os.makedirs(output_dir, exist_ok=True)
def process_tag(tag):
"""
Recursively convert an HTML tag tree into plain text.
- Adds explicit new-lines for <br>, <p>, <center>, and <div>.
- Collapses internal whitespace for text nodes.
"""
fragments = []
# Line-break–type tags
if tag.name in ('br', 'p', 'center'):
for child in tag.children:
fragments.append(process_tag(child))
fragments.append('\n')
return ''.join(fragments)
# Blockquote keeps its old behaviour
if tag.name == 'blockquote':
inner = ''.join(process_tag(child) for child in tag.children)
return inner.strip() + '\n'
# <div>: newline before and after its content
if tag.name == 'div':
inner = ''.join(process_tag(child) for child in tag.children)
return '\n' + inner.strip() + '\n'
# Text node: collapse runs of whitespace
if isinstance(tag, NavigableString):
return re.sub(r'\s+', ' ', tag)
# Any other tag: process children in order
for child in tag.children:
fragments.append(process_tag(child))
return ''.join(fragments)
# Process every .aspx file
for filename in os.listdir(input_dir):
if not filename.lower().endswith('.aspx'):
continue
infile = os.path.join(input_dir, filename)
with open(infile, encoding='utf-8') as f:
html = f.read()
soup = BeautifulSoup(html, 'html.parser')
raw_text = process_tag(soup)
# 1) squeeze spaces around newlines 2) strip leading/trailing whitespace
clean_text = re.sub(r'[ \t]*\n[ \t]*', '\n', raw_text).strip()
outfile = os.path.join(output_dir, os.path.splitext(filename)[0] + '.txt')
with open(outfile, 'w', encoding='utf-8') as f:
f.write(clean_text)
print(f'Processed: {filename} → {outfile}')
Effect:
• Every <div> still becomes
\n(inner text)\n
• But the very first and very last whitespace in the whole file are chopped off, giving you a clean, noise-free plain-text output.