Найти - Пользователи
Полная версия: Есть ли в Python функция аналогичная PHP-функции strip_tags
Начало » Python для новичков » Есть ли в Python функция аналогичная PHP-функции strip_tags
1
tfox
В языке PHP есть функция strip_tags. Она удаляет все html-
теги из текста кроме тех которые определил пользователь. Например.
strip_tags(text_html, “<b><i><u>”) удалит все теги, кроме выделения
жирным, курсива, подчеркивания.
Вот здесь подробнее: http://php.net/manual/en/function.strip-tags.php

Подскажите есть ли эквивалентная функция в Python?
fata1ex
В стандарте такой функции нет, насколько я знаю. Можете посмотреть всевозможные html-парсеры или написать ручками.
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)
PooH
Я для такого использовал lxml.html.clean
tfox
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)

Нет. Данный код выбирает данные которые находятся внутри тегов <h1> и <li>.
Необходимо почистить код от всех тегов, кроме <h1> и <li>.
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)
tfox
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)

Спасибо Работает
py.user.next
при удалении tag
из строки
abc<tag><!-- <tag> --></tag>abc
должна получиться строка
abc<!-- <tag> -->abc
Ed
Тогда так:
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")
py.user.next
из описания функции по ссылке в первом сообщении следует, что она использует конечный автомат
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
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB