Convert HTML to TEXT

インタネットからのデータを処理するとき、HTML、XMLやHTMなどのウェブファイルをテキストファイルに変換しなければならない。
ここで、pythonのいくつかの方法を紹介する。


reを使う方法

reを使う方法

>>> import re
>>> s = 'blah blah <a href="blah">link</a>'
>>> re.sub('<[^>]*>', '', s)
'blah blah link'

この方法は、一番簡単だが、遅くて、変換しないtagもある。

Beautiful Soupを使う方法

BeautifulSoupを使う方法

from BeautifulSoup import BeautifulSoup

html
= "<a> Keep me </a>"
soup
= BeautifulSoup(html)

text_parts
= soup.findAll(text=True)
text
= ''.join(text_parts)
BeautifulSoupライブラリは有名なライブラリである。いろいろなタスクに適用できる。

NLTKを使う方法

NLTKを使う方法


regexs, BeautifulSoup, html2textは、'>'文字をあまりよく処理できない。

自分の経験により、NLTK を使う方法は、一番いいと思う。ただし、NLTKは大きなライブラリだから、インストールがちょっと面倒だったり、実行時間も遅い。

"HTML/XML parser"を使う方法

ElementTree

from lxml import etree

str_
= 'blah blah <a href="blah">link</a> END'
root
= etree.fromstring('<html>%s</html>' % str_)
print ''.join(root.itertext())
この方法は、”HTML/XML parser"を基づいて、処理する。 NLTKとほぼ同じ結果を得る。

Unescape(変な文字)

unicodeのファイルを処理するとき、HTMLのタグをクリーニングするだけではない。時々、unicode文字をうまく変換できない。

例えば、ベトナム語の"ǎ"文字は時々、&#x01ce;に変換しまった。

以下の関数でこの問題を解決する。

unescape

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)


Comments