Top / Programming / Python / Python Tips / エンコーディングで使用できない文字を文字実体参照に変換する

エンコーディングで使用できない文字を文字実体参照に変換する

htmlentitydefs.codepoint2nameを使うと、ユニコード文字のコードポイントをHTMLのエンティティ名に変換することができます。

from htmlentitydefs import codepoint2name

s = u'<html><body>cR</body></html>'
f = open('sjis.html', 'w')
for c in s:
    try:
        f.write(c.encode('shift_jis'))
    except UnicodeError:
        f.write('&%s;' % codepoint2name[ord(c)])
f.close()

出力結果

<html><body>&copy;&reg;</body></html>

htmlentitydefs.codepoint2nameを使えば、ファイルに指定したエンコーディングを使い、ブラウザでユニコード文字列を表示することが出来ます。