Naja er stond dit scrippie om na het opslaan van Word documenten als html nog even de mso opmaak zooi uit het Word bestand te halen. Wel geinig dat dat kan als simpele ziel.
En ohja dit bestandje opslaan als cleanword2html.py of verzin zelf
en dan runnen in de console met: python cleanword2html.py in dezelfde map als het bestand dat moet worden schoongemaakt van Word markup.
Dit zei ChatGPT:
from bs4 import BeautifulSoup
import chardet
import os
# Vraag gebruiker om bestandsnaam
input_filename = input("Voer de naam van het HTML-bestand in (bijv. Wordfile-dirty.html): ")
# Bestaat het bestand?
if not os.path.isfile(input_filename):
print(f"Bestand '{input_filename}' niet gevonden.")
exit()
# Detecteer encoding
with open(input_filename, "rb") as f:
raw_data = f.read()
result = chardet.detect(raw_data)
encoding = result['encoding'] or 'utf-8'
# Decodeer met juiste encoding
html = raw_data.decode(encoding)
# Parse HTML
soup = BeautifulSoup(html, "html.parser")
# Verwijder <style> en <script> tags
for tag in soup(["style", "script"]):
tag.decompose()
# Verwijder Word-specifieke klassen, tags en stijl
for tag in soup.find_all(True):
# Verwijder "Mso..." en "WordSection..." klassen
if "class" in tag.attrs:
classes = tag.get("class", [])
tag['class'] = [cls for cls in classes if not cls.startswith("Mso") and not cls.startswith("WordSection")]
if not tag['class']:
del tag['class']
# Verwijder tags met namespace-prefix zoals o:, w:, v:
if ":" in tag.name:
tag.decompose()
# Verwijder inline stijlen zoals "mso-..." en "word-wrap"
for tag in soup.find_all(style=True):
original_style = tag["style"]
cleaned_style = ";".join([
s for s in original_style.split(";")
if not s.strip().startswith("mso-") and "word-wrap" not in s
])
if cleaned_style.strip():
tag["style"] = cleaned_style
else:
del tag["style"]
# Optioneel: verwijder lege <p> tags
for p in soup.find_all("p"):
if not p.get_text(strip=True):
p.decompose()
# Nieuwe bestandsnaam
output_filename = input_filename.replace(".html", "-cleaned.html")
# Schrijf de opgeschoonde HTML
with open(output_filename, "w", encoding="utf-8") as file:
file.write(str(soup.prettify()))
print(f"Opschonen voltooid. Bestand opgeslagen als: {output_filename}")
[Reactie gewijzigd door BasHouse op 14 mei 2025 20:35]