mirror of
https://github.com/Ladebeze66/llm_ticket3.git
synced 2025-12-15 21:16:52 +01:00
68 lines
2.4 KiB
Python
68 lines
2.4 KiB
Python
# extract_text_from_html.py
|
|
|
|
import os
|
|
import argparse
|
|
from bs4 import BeautifulSoup, Tag
|
|
|
|
def parse_args():
|
|
parser = argparse.ArgumentParser(description="Extrait le texte pur d'un fichier HTML.")
|
|
parser.add_argument("--input", "-i", default="extracted_message/message_228942_clean.html",
|
|
help="Fichier HTML à traiter")
|
|
parser.add_argument("--output", "-o", default="extracted_message/message_text.txt",
|
|
help="Fichier texte de sortie")
|
|
parser.add_argument("--preserve-images", "-p", action="store_true",
|
|
help="Préserver les références aux images")
|
|
return parser.parse_args()
|
|
|
|
def extract_text(html_file, output_file, preserve_images=False):
|
|
"""Extrait le texte d'un fichier HTML et le sauvegarde dans un fichier texte."""
|
|
if not os.path.exists(html_file):
|
|
print(f"❌ Fichier non trouvé : {html_file}")
|
|
return False
|
|
|
|
# Créer le répertoire de sortie si nécessaire
|
|
output_dir = os.path.dirname(output_file)
|
|
if output_dir and not os.path.exists(output_dir):
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
|
|
# Charger et parser le HTML
|
|
with open(html_file, "r", encoding="utf-8") as f:
|
|
html_content = f.read()
|
|
|
|
soup = BeautifulSoup(html_content, "html.parser")
|
|
|
|
# Supprimer les balises vides et inutiles
|
|
for tag in soup.find_all():
|
|
if isinstance(tag, Tag):
|
|
if not tag.get_text(strip=True):
|
|
tag.decompose()
|
|
|
|
# Extraire le texte avec une meilleure mise en forme
|
|
paragraphs = []
|
|
|
|
# Traiter les paragraphes
|
|
for p in soup.find_all("p"):
|
|
if isinstance(p, Tag):
|
|
text = p.get_text(strip=True)
|
|
if text: # Ignorer les paragraphes vides
|
|
paragraphs.append(text)
|
|
|
|
# Traiter les images si demandé
|
|
if preserve_images:
|
|
for img in soup.find_all("img"):
|
|
if isinstance(img, Tag) and img.has_attr("src"):
|
|
paragraphs.append(f"[IMAGE: {img['src']}]")
|
|
|
|
# Créer le texte final avec une structure claire
|
|
text_content = "\n\n".join(paragraphs)
|
|
|
|
# Sauvegarder le texte
|
|
with open(output_file, "w", encoding="utf-8") as f:
|
|
f.write(text_content)
|
|
|
|
print(f"✅ Texte extrait et sauvegardé dans : {output_file}")
|
|
return True
|
|
|
|
if __name__ == "__main__":
|
|
args = parse_args()
|
|
extract_text(args.input, args.output, args.preserve_images) |