Below is an example Python script that reads all HTML files from a folder named justify, extracts the textual content using BeautifulSoup, and writes the cleaned text to new .txt files in a folder named clean.
Make sure you have BeautifulSoup installed (e.g., via pip install beautifulsoup4) before running the script.
import os
from bs4 import BeautifulSoup
# Define folder paths
input_folder = "justify"
output_folder = "clean"
# Create the output folder if it doesn't exist.
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Loop over every file in the input folder.
for filename in os.listdir(input_folder):
# Process only HTML files (you can adjust the extension check if needed).
if filename.lower().endswith(".html"):
input_path = os.path.join(input_folder, filename)
with open(input_path, "r", encoding="utf-8") as file:
html_content = file.read()
# Use BeautifulSoup to parse the HTML content.
soup = BeautifulSoup(html_content, "html.parser")
# Extract plain text from the HTML, using newline as a separator between blocks.
text_content = soup.get_text(separator="\n").strip()
# Define the output .txt filename.
base_name = os.path.splitext(filename)[0]
output_filename = base_name + ".txt"
output_path = os.path.join(output_folder, output_filename)
# Write the cleaned text to the new file.
with open(output_path, "w", encoding="utf-8") as out_file:
out_file.write(text_content)
print(f"Converted '{filename}' to '{output_filename}'.")
How the Script Works
-
Folders Setup:
- It sets the input folder as
justify and the output folder as clean.
- If the
clean folder doesn't exist, it creates it.
-
Processing Files:
- It iterates over each file in the
justify folder and checks for files ending with .html.
- For each HTML file, it reads the file content.
-
Extracting Text:
- The script uses BeautifulSoup to parse the HTML and extracts the text while preserving simple formatting (each block separated by a newline).
-
Output:
- The cleaned text is saved as a
.txt file in the clean folder, preserving the original filename (but with a .txt extension).
Simply run the script in the same directory where your justify folder is located, and the processed text files will appear in the clean folder.