def delinkify(text, allow_domains=None, allow_relative=False):
    """Remove links from text, except those allowed to stay."""
    text = force_unicode(text)
    if not text:
        return u''

    parser = html5lib.HTMLParser(tokenizer=HTMLSanitizer)
    forest = parser.parseFragment(text)

    if allow_domains is None:
        allow_domains = []
    elif isinstance(allow_domains, basestring):
        allow_domains = [allow_domains]

    def delinkify_nodes(tree):
        """Remove <a> tags and replace them with their contents."""
        for node in tree.childNodes:
            if node.name == 'a':
                if 'href' not in node.attributes:
                    continue
                parts = urlparse.urlparse(node.attributes['href'])
                host = parts.hostname
                if any(_domain_match(host, d) for d in allow_domains):
                    continue
                if host is None and allow_relative:
                    continue
                # Replace the node with its children.
                # You can't nest <a> tags, and html5lib takes care of that
                # for us in the tree-building step.
                for n in node.childNodes:
                    tree.insertBefore(n, node)
                tree.removeChild(node)
            elif node.type != NODE_TEXT: # Don't try to delinkify text.
                delinkify_nodes(node)

    delinkify_nodes(forest)
    return _render(forest)
dataset/ETHPy150Open livid/v2ex/v2ex/babel/ext/bleach/__init__.py/delinkify/original