このテキストには画像タグのみが含まれているため、正規表現を使用しても問題ありません。しかし、それ以外の場合は、正真正銘のHTMLパーサーを使用したほうがよいでしょう。幸いなことに、Pythonは1つを提供します!これはかなり必要最低限のものです。完全に機能させるには、さらに多くのコーナーケースを処理する必要があります。(特に、XHTMLスタイルの空のタグ(スラッシュで終わる<... />
)はここでは正しく処理されません。)
>>> from HTMLParser import HTMLParser
>>>
>>> class TagDropper(HTMLParser):
... def __init__(self, tags_to_drop, *args, **kwargs):
... HTMLParser.__init__(self, *args, **kwargs)
... self._text = []
... self._tags_to_drop = set(tags_to_drop)
... def clear_text(self):
... self._text = []
... def get_text(self):
... return ''.join(self._text)
... def handle_starttag(self, tag, attrs):
... if tag not in self._tags_to_drop:
... self._text.append(self.get_starttag_text())
... def handle_endtag(self, tag):
... self._text.append('</{0}>'.format(tag))
... def handle_data(self, data):
... self._text.append(data)
...
>>> td = TagDropper([])
>>> td.feed('A line of text\nA line of text with an <img url="foo"> tag\nAnother line of text with a <br> tag\n')
>>> print td.get_text()
A line of text
A line of text with an <img url="foo"> tag
Another line of text with a <br> tag
そしてタグをドロップするにはimg
...
>>> td = TagDropper(['img'])
>>> td.feed('A line of text\nA line of text with an <img url="foo"> tag\nAnother line of text with a <br> tag\n')
>>> print td.get_text()
A line of text
A line of text with an tag
Another line of text with a <br> tag