Форум сайта python.su
В языке PHP есть функция strip_tags. Она удаляет все html-
теги из текста кроме тех которые определил пользователь. Например.
strip_tags(text_html, “<b><i><u>”) удалит все теги, кроме выделения
жирным, курсива, подчеркивания.
Вот здесь подробнее: http://php.net/manual/en/function.strip-tags.php
Подскажите есть ли эквивалентная функция в Python?
Офлайн
В стандарте такой функции нет, насколько я знаю. Можете посмотреть всевозможные html-парсеры или написать ручками.
Офлайн
Оно?
# -*- coding:utf-8 -*- from bs4 import BeautifulSoup import urllib2 s=urllib2.urlopen('http://python.su/forum/topic/14860/') print BeautifulSoup(s).findAll(['h1', 'li'], text=True)
Офлайн
Я для такого использовал lxml.html.clean
Офлайн
FishHook
Оно?# -*- coding:utf-8 -*- from bs4 import BeautifulSoup import urllib2 s=urllib2.urlopen('http://python.su/forum/topic/14860/') print BeautifulSoup(s).findAll(['h1', 'li'], text=True)
Офлайн
A так?
import re def strip_tags(html, exceptions=None): def repl(match): matched = match.group(0) tag = matched.replace('/', '') if exceptions and tag in exceptions: return matched return re.sub("<[^>]+>", repl, html)
Отредактировано Ed (Июнь 22, 2012 19:56:53)
Офлайн
Ed
A так?import re def strip_tags(html, exceptions=None): def repl(match): matched = match.group(0) tag = matched.replace('/', '') if exceptions and tag in exceptions: return matched return re.sub("<[^>]+>", repl, html)
Офлайн
при удалении tag
из строки
abc<tag><!-- <tag> --></tag>abc
abc<!-- <tag> -->abc
Офлайн
Тогда так:
import re
class Stripper(object):
def __init__(self):
self.incomment = 0
def strip(self, html, exceptions=None):
def repl(match):
matched = match.group(0)
if matched == '<!--':
self.incomment += 1
elif matched == '-->':
self.incomment -= 1
elif not self.incomment:
tag = matched.replace('/', '')
if not exceptions or tag not in exceptions:
return ''
return matched
result = re.sub("<!--|-->|<[^>]+?>", repl, html)
self.incomment = 0
return result
print Stripper().strip("abc<tag><!-- <tag> --></tag>abc")
Отредактировано Ed (Июнь 23, 2012 13:34:25)
Офлайн
из описания функции по ссылке в первом сообщении следует, что она использует конечный автомат
It uses the same tag stripping state machine as the fgetss() function.
<tag><img alt="abc<tag>def" src="pic.png"></tag>
<img alt="abc<tag>def" src="pic.png">
<style>
/* style for <tag> */
tag { color: #ffffff; }
</style><tag>abc</tag>
<style>
/* style for <tag> */
tag { color: #ffffff; }
</style>abc
Отредактировано py.user.next (Июнь 24, 2012 06:18:16)
Офлайн