Python で XML/HTML エンティティを Unicode 文字列に変換する [重複]

StackOverflow https://stackoverflow.com/questions/57708

  •  09-06-2019
  •  | 
  •  

質問

この質問にはすでに答えがあります:

私は Web スクレイピングを行っていますが、サイトでは非 ASCII 文字を表すために HTML エンティティを頻繁に使用しています。Python には、HTML エンティティを含む文字列を受け取り、Unicode 型を返すユーティリティはありますか?

例えば:

戻ります:

ǎ

これは声調記号付きの「Ǝ」を表します。バイナリでは、これは 16 ビットの 01ce として表されます。HTMLエンティティを値に変換したい u'\u01ce'

役に立ちましたか?

解決

標準ライブラリの独自の HTMLParser には、ドキュメントに記載されていない関数 unescape() があり、これはまさに皆さんが考えていることを実行します。

import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('© 2010') # u'\xa9 2010'
h.unescape('© 2010') # u'\xa9 2010'

他のヒント

Python には、 htmlentitydefs モジュールですが、これには HTML エンティティをエスケープ解除する関数は含まれていません。

Python 開発者の Fredrik Lundh (Elementtree などの作者) はそのような機能を持っています 彼のウェブサイトで, 、これは 10 進数、16 進数、および名前付きエンティティで動作します。

import re, htmlentitydefs

##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.

def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)

組み込みを使用する unichr -- BeautifulSoup は必要ありません。

>>> entity = '&#x01ce'
>>> unichr(int(entity[3:],16))
u'\u01ce'

lxml がある場合の代替方法:

>>> import lxml.html
>>> lxml.html.fromstring('&#x01ce').text
u'\u01ce'

Python 3.4 以降を使用している場合は、単に html.unescape:

import html

s = html.unescape(s)

ここで答えが見つかるかもしれません -- Web ページから国際文字を取得しますか?

編集:どうやら BeautifulSoup 16 進形式で書かれたエンティティは変換しません。それは修正できます:

import copy, re
from BeautifulSoup import BeautifulSoup

hexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
# replace hexadecimal character reference by decimal one
hexentityMassage += [(re.compile('&#x([^;]+);'), 
                     lambda m: '&#%d;' % int(m.group(1), 16))]

def convert(html):
    return BeautifulSoup(html,
        convertEntities=BeautifulSoup.HTML_ENTITIES,
        markupMassage=hexentityMassage).contents[0].string

html = '<html>&#x01ce;&#462;</html>'
print repr(convert(html))
# u'\u01ce\u01ce'

編集:

unescape() によって言及された機能 @dF を使用する htmlentitydefs 標準モジュールと unichr() この場合は、の方が適切かもしれません。

これは、正しく処理してエンティティを utf-8 文字に変換するのに役立つ関数です。

def unescape(text):
   """Removes HTML or XML character references 
      and entities from a text string.
   @param text The HTML (or XML) source text.
   @return The plain text, as a Unicode string, if necessary.
   from Fredrik Lundh
   2008-01-03: input only unicode characters string.
   http://effbot.org/zone/re-sub.htm#unescape-html
   """
   def fixup(m):
      text = m.group(0)
      if text[:2] == "&#":
         # character reference
         try:
            if text[:3] == "&#x":
               return unichr(int(text[3:-1], 16))
            else:
               return unichr(int(text[2:-1]))
         except ValueError:
            print "Value Error"
            pass
      else:
         # named entity
         # reescape the reserved characters.
         try:
            if text[1:-1] == "amp":
               text = "&amp;amp;"
            elif text[1:-1] == "gt":
               text = "&amp;gt;"
            elif text[1:-1] == "lt":
               text = "&amp;lt;"
            else:
               print text[1:-1]
               text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
         except KeyError:
            print "keyerror"
            pass
      return text # leave as is
   return re.sub("&#?\w+;", fixup, text)

スタックオーバーフロースレッドに「;」が含まれない理由がわかりません。検索/交換(つまり、ラムダm:'&#%d*;*') そうしないと、隣接する文字が HTML コードの一部として解釈される可能性があるため (つまり、&#39B は &#39ブラックアウト)。

これは私にとってよりうまくいきました:

import re
from BeautifulSoup import BeautifulSoup

html_string='<a href="/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL"title="">&#x27;Blackout in a can; on some shelves despite ban</a>'

hexentityMassage = [(re.compile('&#x([^;]+);'), 
lambda m: '&#%d;' % int(m.group(1), 16))]

soup = BeautifulSoup(html_string, 
convertEntities=BeautifulSoup.HTML_ENTITIES, 
markupMassage=hexentityMassage)
  1. int(m.group(1), 16) は、数値 (base-16 で指定) 形式を整数に変換します。
  2. m.group(0) は一致全体を返し、m.group(1) は正規表現キャプチャ グループを返します。
  3. 基本的に markupMessage の使用方法は次と同じです。
    html_string = re.sub('&#x([^;]+);', ラムダ m:'&#%d;' %int(m.group(1)、16)、html_string)

もう 1 つの解決策は、組み込みライブラリ xml.sax.saxutils (html と xml の両方) です。ただし、変換されるのは &gt、&amp、&lt のみです。

from xml.sax.saxutils import unescape

escaped_text = unescape(text_to_escape)

Python 3 バージョンは次のとおりです。 DFの答え:

import re
import html.entities

def unescape(text):
    """
    Removes HTML or XML character references and entities from a text string.

    :param text:    The HTML (or XML) source text.
    :return:        The plain text, as a Unicode string, if necessary.
    """
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return chr(int(text[3:-1], 16))
                else:
                    return chr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = chr(html.entities.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)

主な変更点は htmlentitydefs それは今です html.entities そして unichr それは今です chr. 。これを参照してください Python 3 移植ガイド.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top