If I'm not mistaken, in python, there's no standard library to convert
html entities, like & or > into their applicable characters.
htmlentitydefs provides maps that helps this conversion,
but it's not a function so you have to write your own function
make use of htmlentitydefs, probably using regex or something.
To me this seemed odd because python is known as
'Batteries Included' language.
So my questions are
1. Why doesn't python have/need entity encoding/decoding?
2. Is there any idiom to do entity encode/decode in python?
Thank you in advance...
import re
from htmlentitydefs import name2codepoint
def htmlentitydecode(s):
return re.sub('&(%s);' % '|'.join(name2codepoint), lambda m:
name2codepoint[m.group(1)], s)
How strange that this doesn't appear in the Cookbook! I'm
curious about how others think: does such an item better
belong in the Cookbook, or the Wiki?
'&(%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.
Regards,
Thomas Jollans
A. I *think* you meant
import re
from htmlentitydefs import name2codepoint
def htmlentitydecode(s):
return re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: chr(name2codepoint[m.group(1)]), s)
We're stretching the limits of what's comfortable
for me as a one-liner.
B. How's it happen this isn't in the Cookbook? I'm
curious about what other Pythoneers think: is
this better memorialized in the Cookbook or the
Wiki?
I think this is the standard idiom:
>>> import xml.sax.saxutils as saxutils
>>> saxutils.escape("&")
'&'
>>> saxutils.unescape(">")
'>'
>>> saxutils.unescape("A bunch of text with entities: & > <")
'A bunch of text with entities: & > <'
Notice there is an optional parameter (a dict) that can be used to
define additional entities as well.
Matt
It's possible that your solution is to a different problem than the original
poster intended. <URL: http://wiki.python.org/moin/EscapingHtml > has de-
tails about HTML entities vs. XML entities.
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és 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"&"), u"&")
self.assertEqual(unescape_charref(u"—"), u"\N{EM DASH}")
self.assertEqual(unescape_charref(u"—"), u"\N{EM DASH}")
def test_unescape(self):
self.assertEqual(
unescape(u"& < — — —"),
u"& < %s %s %s" % tuple(u"\N{EM DASH}"*3)
)
self.assertEqual(unescape(u"&a&"), u"&a&")
self.assertEqual(unescape(u"a&"), u"a&")
self.assertEqual(unescape(u"&nonexistent;"), u"&nonexistent;")
unittest.main()
John