本ページは、アフィリエイト広告が含まれています。

テクノロジー

nltkのnltk.clean_html()を使うと「NotImplementedError: To remove HTML markup, use BeautifulSoup's get_text() function」というエラーが出る場合の対処法

2016年7月6日

Python
文字実
この記事は、株式会社シグマ・デザイン社長の文字実が執筆しました。

久しぶりにNLTKを使ってライバルサイトの調査をしようとしたら、nltk.clean()の行で以下のエラーが出た。

NotImplementedError: To remove HTML markup, use BeautifulSoup's get_text() function

調べてみるとNLTKのバージョン3以上からはnltk.clean_html()とnltk.clean_url()が使えなくなったらしい。

その代わりにBeautifulSoupのget_text()を使えということらしい。

ただ、BeautifulSoupのget_text()はJavaScriptのタグが除去できません。

だからJavaScriptのコードを除去するコードを自分で追加しないといけません。

探してみるとありました。

自分で以下のclean_htmlという関数を追加しました。

参考:Python nltk.clean_html not implemented - Stack Overflow


def clean_html(html):
    """
    Copied from NLTK package.
    Remove HTML markup from the given string.

    :param html: the HTML string to be cleaned
    :type html: str
    :rtype: str
    """

    # First we remove inline JavaScript/CSS:
    cleaned = re.sub(r"(?is)<(script|style).*?>.*?(</1>)", "", html.strip())
    # Then we remove html comments. This has to be done before removing regular
    # tags since comments can contain '>' characters.
    cleaned = re.sub(r"(?s)[n]?", "", cleaned)
    # Next we can remove the remaining tags:
    cleaned = re.sub(r"(?s)<.*?>", " ", cleaned)
    # Finally, we deal with whitespace
    cleaned = re.sub(r" ", " ", cleaned)
    cleaned = re.sub(r"  ", " ", cleaned)
    cleaned = re.sub(r"  ", " ", cleaned)
return cleaned.strip()

参考にさせていただいたサイトのコメントの部分を見るとどうやら以前のclean_html関数の部分をそのまま持ってきたようですね。

もっと複雑なことをしてるのかと思ったけど、ほんの数行で処理していることにびっくり。

それにしてもめんどくさい。なんで無くなったんだろう。

-テクノロジー
-,

Copyright© シグマデザイン社長のブログ , 2024 All Rights Reserved.