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
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 elements like blockquote or div (they often represent a block-level element)
if tag.name in ['blockquote', 'div']:
text_fragments.append('\n') #New Line before
inner = ''.join(process_tag(child) for child in tag.children)
# Append a newline at the end of the block content
text_fragments.append(inner.strip())
text_fragments.append('\n')#New Line after
return ''.join(text_fragments)
# 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()
# 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}")
Newlines Before and After div and blockquote: The most crucial change is the addition of text_fragments.append('\n')before and after processing the children of the div and blockquote tags. This ensures a newline character is inserted at the beginning and end of each block-level element's content, fulfilling the requirement.
Using text_fragments.append consistently: The original code mixed direct string concatenation with using text_fragments.append. The revised code uses text_fragments.append consistently which simplifies the logic and avoids potential errors.
Clarity and Correctness: The changes guarantee that all div and blockquote tags have a newline both before and after their content, addressing the original problem.
This revised code directly addresses the prompt's requirements and provides a clear, maintainable solution for cleaning HTML by adding newlines around div and blockquote elements.