これは、Unicode html エンティティも処理する完全な実装です。役に立つかもしれません。
ascii ではない Unicode 文字列を返しますが、プレーンな ascii が必要な場合は、エンティティを空の文字列に置き換えるように置換操作を変更できます。
def convert_html_entities(s):
matches = re.findall("&#\d+;", s)
if len(matches) > 0:
hits = set(matches)
for hit in hits:
name = hit[2:-1]
try:
entnum = int(name)
s = s.replace(hit, unichr(entnum))
except ValueError:
pass
matches = re.findall("&#[xX][0-9a-fA-F]+;", s)
if len(matches) > 0:
hits = set(matches)
for hit in hits:
hex = hit[3:-1]
try:
entnum = int(hex, 16)
s = s.replace(hit, unichr(entnum))
except ValueError:
pass
matches = re.findall("&\w+;", s)
hits = set(matches)
amp = "&"
if amp in hits:
hits.remove(amp)
for hit in hits:
name = hit[1:-1]
if htmlentitydefs.name2codepoint.has_key(name):
s = s.replace(hit, unichr(htmlentitydefs.name2codepoint[name]))
s = s.replace(amp, "&")
return s
編集:16進コードのマッチングを追加しました。私はこれをしばらく使用しており、単一引用符/アポストロフィである ' を使用した最初の状況に遭遇しました。