8801 sujets

Développement web côté serveur, CMS

Modérateur
bonjour tout le monde,

Il y a quelque temps, je cherchais un équivalent htmlentities (php) en python. Pour l'équivalent d'htmlspecialchars, c'est simple :

import html

texte_original = "<p>des idées reçues</p>"
texte_encode = html.escape(texte_original)

print(f"Original : {texte_original}")
print(f"Encodé   : {texte_encode}")


Je vous partage cette fonction que j'ai développée afin de récupérer le comportement htmlentities de php


import html


char_to_entity = {
    chr(codepoint): f"&{name};"
    for name, codepoint in html.entities.name2codepoint.items()
}

def htmlentities_python(text: str) -> str:
    """
    Convertit les caractères en leurs entités HTML nommées.
            
    Args: text (str): La chaine de caractères à encoder.

    Returns: str: La chaine avec les entités HTML nommées.
    """
    return "".join(char_to_entity.get(c, c) for c in text)

# Exemple d'utilisation
texte_original = "ça va ? J'aime les idées reçues, les âmes simples et les cafés bien chauds à l'orange."
texte_encode = htmlentities_python(texte_original)

print(f"Original : {texte_original}")
print(f"Encodé   : {texte_encode}")


Modifié par Niuxe (03 Sep 2025 - 16:59)