You're right to be frustrated, and I appreciate your patience — let me now give you exactly what you’re asking for.
✅ Your Request Recap:
I have .aspx files in a folder called justify, which are HTML files.
I want to extract only the plain text (no HTML at all),
with newlines only where there are <br> tags.
Output should be .txt files in a folder called clean.
Got it.
✅ What the Script Will Do:
Read each .aspx file in the justify folder.
Parse the HTML.
Extract only plaintext, stripping out all formatting, HTML tags, scripts, styles, etc.
Keep newlines only from <br>. Everything else (e.g., <div>, <p>, etc.) will NOT cause a line break.
Output a .txt file for each, in the clean folder.
🛠️ Python Script
python
import os
from bs4 import BeautifulSoup, NavigableString
input_folder = "justify"
output_folder = "clean"
# Create the output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
def extract_clean_text_only_with_br(html):
soup = BeautifulSoup(html, "html.parser")
parts = []
for element in soup.body.descendants if soup.body else soup.descendants:
if isinstance(element, NavigableString):
# Keep plain text, stripping unnecessary whitespace
text = element.strip()
if text:
parts.append(text)
elif element.name == 'br':
parts.append('\n')
# Join all parts, inserting spaces where needed, then clean up
text = ' '.join(parts)
# Collapse multiple spaces, allow newlines to stay
text = ' '.join(text.split())
text = text.replace('\n ', '\n').replace(' \n', '\n').strip()
return text
# Process each .aspx file in the input folder
for filename in os.listdir(input_folder):
if filename.lower().endswith(".aspx"):
input_path = os.path.join(input_folder, filename)
output_filename = os.path.splitext(filename)[0] + ".txt"
output_path = os.path.join(output_folder, output_filename)
with open(input_path, "r", encoding="utf-8") as f:
html = f.read()
plain_text = extract_clean_text_only_with_br(html)
with open(output_path, "w", encoding="utf-8") as f:
f.write(plain_text)
print(f"✓ Converted: {filename} ➝ {output_filename}")