74

PythonでHTMLエンティティをUnicodeに、またはその逆にどのように変換しますか?

4

9 に答える 9

106

「その逆」については(私は自分自身を必要としていたため、この質問を見つけることになりましたが、役に立ちませんでした。その後、別のサイトに答えがありました):

u'some string'.encode('ascii', 'xmlcharrefreplace')

非ASCII文字をXML(HTML)エンティティに変換したプレーンな文字列を返します。

于 2010-04-17T06:13:38.070 に答える
31

あなたは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
# &, ®, <, >, ¢, £, ¥, €, §, ©
# &amp;, &#174;, &lt;, &gt;, &#162;, &#163;, &#165;, &#8364;, &#167;, &#169;
于 2009-03-31T15:57:56.340 に答える
22

Python 2.7 および BeautifulSoup4 の更新

Unescape -- Unicode HTML から Unicode へhtmlparser(Python 2.7 標準ライブラリ):

>>> escaped = u'Monsieur le Cur&eacute; of the &laquo;Notre-Dame-de-Gr&acirc;ce&raquo; 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&eacute; of the &laquo;Notre-Dame-de-Gr&acirc;ce&raquo; 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&eacute; of the &laquo;Notre-Dame-de-Gr&acirc;ce&raquo; neighborhood'
于 2015-03-03T08:43:24.993 に答える
14

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 エンティティをプレーンテキスト表現に変換する場合。
于 2014-07-09T00:02:40.287 に答える
1

次の関数を使用して、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 = '&nbsp;'
    try:
        f.write(dat.encode('ascii'))
    except:
        f.write(html.escape(dat).encode('ascii', 'xmlcharrefreplace'))

これが誰かに役立つことを願っています

于 2017-05-17T14:18:29.923 に答える