Python 相当于 PHP 的 strip_tags?

发布于 2024-08-22 08:09:26 字数 174 浏览 9 评论 0原文

Python 相当于 PHP 的 strip_tags?

http://php.net/manual/en/function.strip-tags.php

Python's equivalent to PHP's strip_tags?

http://php.net/manual/en/function.strip-tags.php

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

注定孤独终老 2024-08-29 08:09:26

Python 标准库中没有这样的东西。这是因为 Python 是一种通用语言,而 PHP 最初是一种面向 Web 的语言。

尽管如此,您有 3 个解决方案:

  • 您很着急:自己做一个。 re.sub(r'<[^>]*?>', '', value) 可能是一个快速但肮脏的解决方案。
  • 使用第三方库(推荐,因为更防弹):beautiful soup 是一个非常好的库无需安装任何内容,只需复制 lib 目录并导入即可。 完整的教程和漂亮的汤
  • 使用框架。大多数 Web Python 开发人员从不从头开始编写代码,他们使用诸如 django 之类的框架来自动为您完成这些工作。 django 完整教程

There is no such thing in the Python standard library. It's because Python is a general purpose language while PHP started as a Web oriented language.

Nevertheless, you have 3 solutions:

  • You are in a hurry: just make your own. re.sub(r'<[^>]*?>', '', value) can be a quick and dirty solution.
  • Use a third party library (recommended because more bullet proof) : beautiful soup is a really good one and there is nothing to install, just copy the lib dir and import. Full tuto with beautiful soup.
  • Use a framework. Most Web Python devs never code from scratch, they use a framework such as django that does automatically this stuff for you. Full tuto with django.
梦初启 2024-08-29 08:09:26

使用BeautifulSoup

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(htmltext)
''.join([e for e in soup.recursiveChildGenerator() if isinstance(e,unicode)])

Using BeautifulSoup

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(htmltext)
''.join([e for e in soup.recursiveChildGenerator() if isinstance(e,unicode)])
北城孤痞 2024-08-29 08:09:26
from bleach import clean
print clean("<strong>My Text</strong>", tags=[], strip=True, strip_comments=True)
from bleach import clean
print clean("<strong>My Text</strong>", tags=[], strip=True, strip_comments=True)
梦醒时光 2024-08-29 08:09:26

您不会找到许多内置 PHP HTML 函数的内置 Python 等效项,因为 Python 更像是一种通用脚本语言,而不是 Web 开发语言。对于 HTML 处理,通常建议使用 BeautifulSoup

You won't find many builtin Python equivalents for builtin PHP HTML functions since Python is more of a general-purpose scripting language than a web development language. For HTML processing, BeautifulSoup is generally recommended.

分開簡單 2024-08-29 08:09:26

我使用 HTMLParser 类为 Python 3 构建了一个。它比 PHP 更详细。我将其称为 HTMLCleaner 类,您可以找到源代码 在这里,您可以找到示例

I built one for Python 3 using the HTMLParser class. It is more verbose than PHP's. I called it the HTMLCleaner class, and you can find the source here and you can find examples here.

丑丑阿 2024-08-29 08:09:26

有一个有效的状态配方,

http://code.activestate.com/recipes/52281/< /a>

这是旧代码,因此您必须将 sgml 解析器更改为 HTMLparser,如注释中所述

这是修改后的代码,

import HTMLParser, string

class StrippingParser(HTMLParser.HTMLParser):

    # These are the HTML tags that we will leave intact
    valid_tags = ('b', 'a', 'i', 'br', 'p', 'img')

    from htmlentitydefs import entitydefs # replace entitydefs from sgmllib

    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self.result = ""
        self.endTagList = []

    def handle_data(self, data):
        if data:
            self.result = self.result + data

    def handle_charref(self, name):
        self.result = "%s&#%s;" % (self.result, name)

    def handle_entityref(self, name):
        if self.entitydefs.has_key(name): 
            x = ';'
        else:
            # this breaks unstandard entities that end with ';'
            x = ''
        self.result = "%s&%s%s" % (self.result, name, x)

    def handle_starttag(self, tag, attrs):
        """ Delete all tags except for legal ones """
        if tag in self.valid_tags:       
            self.result = self.result + '<' + tag
            for k, v in attrs:
                if string.lower(k[0:2]) != 'on' and string.lower(v[0:10]) != 'javascript':
                    self.result = '%s %s="%s"' % (self.result, k, v)
            endTag = '</%s>' % tag
            self.endTagList.insert(0,endTag)    
            self.result = self.result + '>'

    def handle_endtag(self, tag):
        if tag in self.valid_tags:
            self.result = "%s</%s>" % (self.result, tag)
            remTag = '</%s>' % tag
            self.endTagList.remove(remTag)

    def cleanup(self):
        """ Append missing closing tags """
        for j in range(len(self.endTagList)):
                self.result = self.result + self.endTagList[j]    


def strip(s):
    """ Strip illegal HTML tags from string s """
    parser = StrippingParser()
    parser.feed(s)
    parser.close()
    parser.cleanup()
    return parser.result

There is an active state recipe for this,

http://code.activestate.com/recipes/52281/

It's old code so you have to change sgml parser to HTMLparser as mentioned in the comments

Here is the modified code,

import HTMLParser, string

class StrippingParser(HTMLParser.HTMLParser):

    # These are the HTML tags that we will leave intact
    valid_tags = ('b', 'a', 'i', 'br', 'p', 'img')

    from htmlentitydefs import entitydefs # replace entitydefs from sgmllib

    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self.result = ""
        self.endTagList = []

    def handle_data(self, data):
        if data:
            self.result = self.result + data

    def handle_charref(self, name):
        self.result = "%s&#%s;" % (self.result, name)

    def handle_entityref(self, name):
        if self.entitydefs.has_key(name): 
            x = ';'
        else:
            # this breaks unstandard entities that end with ';'
            x = ''
        self.result = "%s&%s%s" % (self.result, name, x)

    def handle_starttag(self, tag, attrs):
        """ Delete all tags except for legal ones """
        if tag in self.valid_tags:       
            self.result = self.result + '<' + tag
            for k, v in attrs:
                if string.lower(k[0:2]) != 'on' and string.lower(v[0:10]) != 'javascript':
                    self.result = '%s %s="%s"' % (self.result, k, v)
            endTag = '</%s>' % tag
            self.endTagList.insert(0,endTag)    
            self.result = self.result + '>'

    def handle_endtag(self, tag):
        if tag in self.valid_tags:
            self.result = "%s</%s>" % (self.result, tag)
            remTag = '</%s>' % tag
            self.endTagList.remove(remTag)

    def cleanup(self):
        """ Append missing closing tags """
        for j in range(len(self.endTagList)):
                self.result = self.result + self.endTagList[j]    


def strip(s):
    """ Strip illegal HTML tags from string s """
    parser = StrippingParser()
    parser.feed(s)
    parser.close()
    parser.cleanup()
    return parser.result
冰雪梦之恋 2024-08-29 08:09:26

Python 没有内置函数,但实现数量多得惊人

Python doesn't have one built-in, but there are an ungodly number of implementations.

节枝 2024-08-29 08:09:26

使用 beautifulsoup4,

def strip_tags(html_content):
    soup = bs4.BeautifulSoup(html_content, 'html.parser')
    return soup.get_text()

Using beautifulsoup4,

def strip_tags(html_content):
    soup = bs4.BeautifulSoup(html_content, 'html.parser')
    return soup.get_text()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文