PythonでHTMLエンティティをUnicodeに、またはその逆にどのように変換しますか?
9 に答える
「その逆」については(私は自分自身を必要としていたため、この質問を見つけることになりましたが、役に立ちませんでした。その後、別のサイトに答えがありました):
u'some string'.encode('ascii', 'xmlcharrefreplace')
非ASCII文字をXML(HTML)エンティティに変換したプレーンな文字列を返します。
あなたはBeautifulSoupを持っている必要があります。
from BeautifulSoup import BeautifulStoneSoup
import cgi
def HTMLEntitiesToUnicode(text):
"""Converts HTML entities to unicode. For example '&' becomes '&'."""
text = unicode(BeautifulStoneSoup(text, convertEntities=BeautifulStoneSoup.ALL_ENTITIES))
return text
def unicodeToHTMLEntities(text):
"""Converts unicode to HTML entities. For example '&' becomes '&'."""
text = cgi.escape(text).encode('ascii', 'xmlcharrefreplace')
return text
text = "&, ®, <, >, ¢, £, ¥, €, §, ©"
uni = HTMLEntitiesToUnicode(text)
htmlent = unicodeToHTMLEntities(uni)
print uni
print htmlent
# &, ®, <, >, ¢, £, ¥, €, §, ©
# &, ®, <, >, ¢, £, ¥, €, §, ©
Python 2.7 および BeautifulSoup4 の更新
Unescape -- Unicode HTML から Unicode へhtmlparser
(Python 2.7 標準ライブラリ):
>>> escaped = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood'
>>> from HTMLParser import HTMLParser
>>> htmlparser = HTMLParser()
>>> unescaped = htmlparser.unescape(escaped)
>>> unescaped
u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood'
>>> print unescaped
Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood
Unescape -- Unicode HTML から Unicode へbs4
(BeautifulSoup4):
>>> html = '''<p>Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood</p>'''
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> soup.text
u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood'
>>> print soup.text
Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood
bs4
エスケープ -- (BeautifulSoup4)を使用した Unicode から Unicode HTML へ:
>>> unescaped = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood'
>>> from bs4.dammit import EntitySubstitution
>>> escaper = EntitySubstitution()
>>> escaped = escaper.substitute_html(unescaped)
>>> escaped
u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood'
hekevintranの回答が示唆するように、文字列のエンコードに使用できますが、cgi.escape(s)
その関数では引用符のエンコードがデフォルトで false であることに注意してquote=True
ください。文字列と一緒にキーワード引数を渡すことをお勧めします。ただし、 を渡してもquote=True
、関数は単一引用符 ( ) をエスケープしません"'"
(これらの問題のため、この関数はバージョン 3.2 以降非推奨になっています)。
html.escape(s)
の代わりに使用することが提案されていますcgi.escape(s)
。(バージョン 3.2 の新機能)
また、バージョン 3.4 で導入されましhtml.unescape(s)
た。
したがって、Python 3.4 では次のことができます。
html.escape(text).encode('ascii', 'xmlcharrefreplace').decode()
特殊文字を HTML エンティティに変換するために使用します。- また
html.unescape(text)
、HTML エンティティをプレーンテキスト表現に変換する場合。
次の関数を使用して、xls ファイルにある特殊文字を保持しながら、xls ファイルからリッピングされた Unicode を html ファイルに変換しました。
def html_wr(f, dat):
''' write dat to file f as html
. file is assumed to be opened in binary format
. if dat is nul it is replaced with non breakable space
. non-ascii characters are translated to xml
'''
if not dat:
dat = ' '
try:
f.write(dat.encode('ascii'))
except:
f.write(html.escape(dat).encode('ascii', 'xmlcharrefreplace'))
これが誰かに役立つことを願っています