Account Options

  1. Sign in
The old Google Groups will be going away soon, but your browser is incompatible with the new version.
Google Groups Home
« Groups Home
Message from discussion How do you htmlentities in Python
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
John J. Lee  
View profile  
 More options Jun 6 2007, 6:07 pm
Newsgroups: comp.lang.python
From: j...@pobox.com (John J. Lee)
Date: Wed, 06 Jun 2007 22:07:36 GMT
Local: Wed, Jun 6 2007 6:07 pm
Subject: Re: How do you htmlentities in Python

"Thomas Jollans" <tho...@jollans.NOSPAM.com> writes:
> "Adam Atlas" <a...@atlas.st> wrote in message
> news:1180965792.757685.132580@q75g2000hsh.googlegroups.com...
> > As far as I know, there isn't a standard idiom to do this, but it's
> > still a one-liner. Untested, but I think this should work:

> > import re
> > from htmlentitydefs import name2codepoint
> > def htmlentitydecode(s):
> >    return re.sub('&(%s);' % '|'.join(name2codepoint), lambda m:
> >         name2codepoint[m.group(1)], s)

> '&(%s);' won't quite work: HTML (and, I assume, SGML, but not XHTML being
> XML) allows you to skip the semicolon after the entity if it's followed by a
> white space (IIRC). Should this be respected, it looks more like this:
> r'&(%s)([;\s]|$)'

> Also, this completely ignores non-name entities as also found in XML. (eg
> %x20; for ' ' or so) Maybe some part of the HTMLParser module is useful, I
> wouldn't know. IMHO, these particular batteries aren't too commonly needed.

Here's one that handles numeric character references, and chooses to
leave entity references that are not defined in standard library
module htmlentitydefs intact, rather than throwing an exception.

It ignores the missing semicolon issue (and note also that IE can cope
with even a missing space, like "tr&eacutes mal", so you'll see that
in the wild).  Probably it could be adapted to handle that (possibly
the presumably-slower htmllib-based recipe on the python.org wiki
already does handle that, not sure).

import htmlentitydefs
import re
import unittest

def unescape_charref(ref):
    name = ref[2:-1]
    base = 10
    if name.startswith("x"):
        name = name[1:]
        base = 16
    return unichr(int(name, base))

def replace_entities(match):
    ent = match.group()
    if ent[1] == "#":
        return unescape_charref(ent)

    repl = htmlentitydefs.name2codepoint.get(ent[1:-1])
    if repl is not None:
        repl = unichr(repl)
    else:
        repl = ent
    return repl

def unescape(data):
    return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data)

class UnescapeTests(unittest.TestCase):

    def test_unescape_charref(self):
        self.assertEqual(unescape_charref(u"&#38;"), u"&")
        self.assertEqual(unescape_charref(u"&#x2014;"), u"\N{EM DASH}")
        self.assertEqual(unescape_charref(u"&#8212;"), u"\N{EM DASH}")

    def test_unescape(self):
        self.assertEqual(
            unescape(u"&amp; &lt; &mdash; &#8212; &#x2014;"),
            u"& < %s %s %s" % tuple(u"\N{EM DASH}"*3)
            )
        self.assertEqual(unescape(u"&a&amp;"), u"&a&")
        self.assertEqual(unescape(u"a&amp;"), u"a&")
        self.assertEqual(unescape(u"&nonexistent;"), u"&nonexistent;")

unittest.main()

John


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.