我已经看到了一些关于从字符串中删除HTML标记的问题,但我仍然不清楚应该如何处理我的特定情况。
我已经看到许多帖子建议不要使用正则表达式来处理HTML,但我怀疑我的案例可能会明智地规避这条规则。
我正在尝试解析PDF文件,并且我已经成功地将每个页面从我的示例PDF文件转换为UTF-32文本字符串。当图像出现时,会插入一个HTML样式的标签,其中包含图像的名称和位置(在其他地方保存)。
在我的应用程序的一个单独部分,我需要摆脱这些图像标签。因为我们只处理图像标签,所以我怀疑可能需要使用正则表达式。
我的问题是双重的:
为清楚起见,标签的结构为<img src="/path/to/file"/>
谢谢!
我会投票,在你的情况下,使用正则表达式是可以接受的。这样的事情应该有效:
def remove_html_tags(data):
p = re.compile(r'<.*?>')
return p.sub('', data)
我在这里找到了这个片段(http://love-python.blogspot.com/2008/07/strip-html-tags-using-python.html)
编辑:版本只会删除<img .... />
形式的东西:
def remove_img_tags(data):
p = re.compile(r'<img.*?/>')
return p.sub('', data)
由于此文本仅包含图像标记,因此使用正则表达式可能没问题。但对于其他任何事情,你可能最好使用真正的HTML解析器。幸运的是Python提供了一个!这是非常简单的 - 要完全正常运行,这将需要处理更多的极端情况。 (最值得注意的是,这里没有正确处理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
我的解决方案是:
def remove_HTML_tag(tag, string):
string = re.sub(r"<\b(" + tag + r")\b[^>]*>", r"", string)
return re.sub(r"<\/\b(" + tag + r")\b[^>]*>", r"", string)