if not os.path.exists(output_dir):
os.makedirs(output_dir)
def process_tag(tag):
"""
Recursively process the BeautifulSoup tag tree to build a plain-text string.
Inserts explicit newlines for specific tags and collapses whitespace in text nodes.
"""
text_fragments = []
code
# For break-like elements, process children and then add a newline.
if tag.name in ['br', 'p', 'center']:
for child in tag.children:
text_fragments.append(process_tag(child))
text_fragments.append('\n')
return ''.join(text_fragments)
# For elements like blockquote or div (they often represent a block-level element)
if tag.name in ['blockquote', 'div']:
inner = ''.join(process_tag(child) for child in tag.children)
# Append a newline at the end of the block content
return inner.strip() + '\n'
# For text nodes, collapse internal whitespace.
if isinstance(tag, NavigableString):
# Replace multiple whitespace characters with a single space.
return re.sub(r'\s+', ' ', tag)
# For any other tags, process their children consecutively.
for child in tag.children:
text_fragments.append(process_tag(child))
return ''.join(text_fragments)
Process each .aspx file in the input directory.
for filename in os.listdir(input_dir):
if filename.lower().endswith(".aspx"):
infile = os.path.join(input_dir, filename)
with open(infile, 'r', encoding='utf-8') as f:
html_content = f.read()
code
# Parse the HTML content.
soup = BeautifulSoup(html_content, 'html.parser')
# Process the entire HTML tree.
plain_with_newlines = process_tag(soup)
# Cleanup: remove spaces immediately before and after newlines and trim overall text.
plain = re.sub(r'[ \t]*\n[ \t]*', '\n', plain_with_newlines).strip()
# Save the final cleaned text to the output folder with a .txt extension.
base, _ = os.path.splitext(filename)
outfile = os.path.join(output_dir, base + ".txt")
with open(outfile, 'w', encoding='utf-8') as f:
f.write(plain)
print(f"Processed: {filename} -> {outfile}")
Modify this code, ensure that start and end of div is a newline
Assistant
To ensure that the start and end of every <div> tag in the HTML input are represented by a newline character (\n) in the resulting plain-text output, we need to make two key modifications to the original code:
✅ 1. Update the process_tag Function for <div> Tags
We need to explicitly wrap the contents of each <div> in \n at both the start and end, ensuring that the div always appears on its own line in the final output.
This means separating the handling of <div> from <blockquote>, since the user only wants this behavior for <div> tags.
Revised Code Snippet:
python
if tag.name == 'blockquote':
inner = ''.join(process_tag(child) for child in tag.children)
return inner.strip() + '\n'
if tag.name == 'div':
inner = ''.join(process_tag(child) for child in tag.children)
return '\n' + inner.strip() + '\n'
This ensures that every <div> results in content like:
code
\ninner content\n
✅ 2. Remove the Final .strip() Call in the Cleanup Step
Here is the complete modified version of your script with the above changes:
python
import os
import re
from bs4 import BeautifulSoup, NavigableString
# Input and output directories
input_dir = 'justify'
output_dir = 'clean'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
def process_tag(tag):
"""
Recursively process the BeautifulSoup tag tree to build a plain-text string.
Inserts explicit newlines for specific tags and collapses whitespace in text nodes.
"""
text_fragments = []
# For break-like elements, process children and then add a newline.
if tag.name in ['br', 'p', 'center']:
for child in tag.children:
text_fragments.append(process_tag(child))
text_fragments.append('\n')
return ''.join(text_fragments)
# For blockquote, keep original behavior
if tag.name == 'blockquote':
inner = ''.join(process_tag(child) for child in tag.children)
return inner.strip() + '\n'
# For div, add newline before and after
if tag.name == 'div':
inner = ''.join(process_tag(child) for child in tag.children)
return '\n' + inner.strip() + '\n'
# For text nodes, collapse internal whitespace.
if isinstance(tag, NavigableString):
return re.sub(r'\s+', ' ', tag)
# For any other tags, process their children consecutively.
for child in tag.children:
text_fragments.append(process_tag(child))
return ''.join(text_fragments)
# Process each .aspx file in the input directory.
for filename in os.listdir(input_dir):
if filename.lower().endswith(".aspx"):
infile = os.path.join(input_dir, filename)
with open(infile, 'r', encoding='utf-8') as f:
html_content = f.read()
# Parse the HTML content.
soup = BeautifulSoup(html_content, 'html.parser')
# Process the entire HTML tree.
plain_with_newlines = process_tag(soup)
# Cleanup: remove spaces immediately before and after newlines
plain = re.sub(r'[ \t]*\n[ \t]*', '\n', plain_with_newlines)
# Save the final cleaned text to the output folder with a .txt extension.
base, _ = os.path.splitext(filename)
outfile = os.path.join(output_dir, base + ".txt")
with open(outfile, 'w', encoding='utf-8') as f:
f.write(plain)
print(f"Processed: {filename} -> {outfile}")
🧪 Example
Input HTML:
html
<div>Hello</div>
<div>World</div>
Output Text:
code
\nHello\n
\nWorld\n
After the regex cleanup:
code
\nHello\n\nWorld\n
Since we removed .strip(), the final output will preserve the leading and trailing newlines:
code
Hello
World
✅ Summary of Changes
Change
Purpose
Wrap <div> content in \n
Ensures each <div> starts and ends with a newline
Remove .strip() from final output
Preserves leading and trailing newlines from <div> tags
Separate handling of <div> and <blockquote>
Ensures only <div> gets the newline wrapping
This updated script now fully satisfies the requirement: every <div> in the input HTML is represented with a newline at both the start and end in the output text.