2009-05-03 11 views

risposta

2

Partenza this question. Quello che stai cercando è "decodifica dell'entità html". In genere, troverai una funzione chiamata "htmldecode" che farà ciò che desideri. Sia Django che Cheetah offrono funzioni come BeautifulSoup.

L'altra risposta funzionerà perfettamente se non si desidera utilizzare una libreria e tutte le entità sono numeriche.

+0

grazie. cosa ha Django? perché ho guardato i documenti ma non ho trovato nulla ... – rick

+0

Si chiama django.utils.html.escape, apparentemente. Controlla l'altra domanda di StackOverflow che ho collegato per ulteriori dettagli. – easel

+0

sembra che django.utils.html.escape funzioni solo per codificare, non per decodificare. ho finito per usare BeautifulSoup. Grazie – rick

-2

io non sono sicuro circa la & o #, ma qui è un codice per la decodifica:

>>>chr(39) 
"'" 
>>>ord("'") 
39 
1

La soluzione più robusta sembra essere il this function del luminare di Python Fredrik Lundh. Non è la soluzione più breve, ma gestisce le entità denominate nonché i codici esadecimale e decimale.

2

Prova questa: (trovato here)

from htmlentitydefs import name2codepoint as n2cp 
import re 

def decode_htmlentities(string): 
    """ 
    Decode HTML entities–hex, decimal, or named–in a string 
    @see http://snippets.dzone.com/posts/show/4569 

    >>> u = u'E tu vivrai nel terrore - L'aldilà (1981)' 
    >>> print decode_htmlentities(u).encode('UTF-8') 
    E tu vivrai nel terrore - L'aldilà (1981) 
    >>> print decode_htmlentities("l'eau") 
    l'eau 
    >>> print decode_htmlentities("foo < bar")     
    foo < bar 
    """ 
    def substitute_entity(match): 
     ent = match.group(3) 
     if match.group(1) == "#": 
      # decoding by number 
      if match.group(2) == '': 
       # number is in decimal 
       return unichr(int(ent)) 
      elif match.group(2) == 'x': 
       # number is in hex 
       return unichr(int('0x'+ent, 16)) 
     else: 
      # they were using a name 
      cp = n2cp.get(ent) 
      if cp: return unichr(cp) 
      else: return match.group() 

    entity_re = re.compile(r'&(#?)(x?)(\w+);') 
    return entity_re.subn(substitute_entity, string)[0] 
Problemi correlati