7

Is there a pure-Python tool to take some HTML and truncate it as close to a given length as possible, but make sure the resulting snippet is well-formed? For example, given this HTML:

<h1>This is a header</h1>
<p>This is a paragraph</p>

it would not produce:

<h1>This is a hea

but:

<h1>This is a header</h1>

or at least:

<h1>This is a hea</h1>

I can't find one that works, though I found one that relies on pullparser, which is both obsolete and dead.

4

8 回答 8

7

我认为您不需要一个成熟的解析器 - 您只需要将输入字符串标记为以下之一:

  • 文本
  • 打开标签
  • 关闭标签
  • 自闭标签
  • 人物实体

一旦你有了这样的标记流,就很容易使用堆栈来跟踪需要关闭的标签。实际上我不久前遇到了这个问题并写了一个小库来做到这一点:

https://github.com/entzel/htmltruncate.py

它对我来说效果很好,并且可以很好地处理大多数极端情况,包括任意嵌套标记、将字符实体计数为单个字符、在格式错误的标记上返回错误等。

它将产生:

<h1>This is a hea</h1>

在你的例子。这可能会改变,但在一般情况下很难 - 如果您尝试截断为 10 个字符,但<h1>标签没有关闭另一个,比如 300 个字符,该怎么办?

于 2011-03-07T19:05:43.943 回答
7

如果您使用的是 DJANGO lib,您可以简单地:

from django.utils import text, html

    class class_name():


        def trim_string(self, stringf, limit, offset = 0):
            return stringf[offset:limit]

        def trim_html_words(self, html, limit, offset = 0):
            return text.truncate_html_words(html, limit)


        def remove_html(self, htmls, tag, limit = 'all', offset = 0):
            return html.strip_tags(htmls)

无论如何,这是来自 django 的 truncate_html_words 的代码:

import re

def truncate_html_words(s, num):
    """
    Truncates html to a certain number of words (not counting tags and comments).
    Closes opened tags if they were correctly closed in the given html.
    """
    length = int(num)
    if length <= 0:
        return ''
    html4_singlets = ('br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input')
    # Set up regular expressions
    re_words = re.compile(r'&.*?;|<.*?>|([A-Za-z0-9][\w-]*)')
    re_tag = re.compile(r'<(/)?([^ ]+?)(?: (/)| .*?)?>')
    # Count non-HTML words and keep note of open tags
    pos = 0
    ellipsis_pos = 0
    words = 0
    open_tags = []
    while words <= length:
        m = re_words.search(s, pos)
        if not m:
            # Checked through whole string
            break
        pos = m.end(0)
        if m.group(1):
            # It's an actual non-HTML word
            words += 1
            if words == length:
                ellipsis_pos = pos
            continue
        # Check for tag
        tag = re_tag.match(m.group(0))
        if not tag or ellipsis_pos:
            # Don't worry about non tags or tags after our truncate point
            continue
        closing_tag, tagname, self_closing = tag.groups()
        tagname = tagname.lower()  # Element names are always case-insensitive
        if self_closing or tagname in html4_singlets:
            pass
        elif closing_tag:
            # Check for match in open tags list
            try:
                i = open_tags.index(tagname)
            except ValueError:
                pass
            else:
                # SGML: An end tag closes, back to the matching start tag, all unclosed intervening start tags with omitted end tags
                open_tags = open_tags[i+1:]
        else:
            # Add it to the start of the open tags list
            open_tags.insert(0, tagname)
    if words <= length:
        # Don't try to close tags if we don't need to truncate
        return s
    out = s[:ellipsis_pos] + ' ...'
    # Close any tags still open
    for tag in open_tags:
        out += '</%s>' % tag
    # Return string
    return out
于 2011-02-13T16:57:12.103 回答
4

我发现 slacy 的答案非常有帮助,如果我有名声,我会支持它,但是还有一件事需要注意。在我的环境中,我安装了 html5lib 和 BeautifulSoup4。BeautifulSoup 使用了 html5lib 解析器,这导致我的 html 片段被包裹在 html 和 body 标记中,这不是我想要的。

>>> truncate_html("<p>sdfsdaf</p>", 4)
u'<html><head></head><body><p>s</p></body></html>'

为了解决这些问题,我告诉 BeautifulSoup 使用 python 解析器:

from bs4 import BeautifulSoup
def truncate_html(html, length): 
    return unicode(BeautifulSoup(html[:length], "html.parser"))

>>> truncate_html("<p>sdfsdaf</p>", 4)
u'<p>s</p>'
于 2012-02-09T05:13:20.160 回答
3

您可以使用 BeautifulSoup 在一行中执行此操作(假设您要截断一定数量的源字符,而不是多个内容字符):

from BeautifulSoup import BeautifulSoup

def truncate_html(html, length): 
    return unicode(BeautifulSoup(html[:length]))
于 2011-12-08T17:02:08.870 回答
2

这将满足您的要求。易于使用的 HTML 解析器和错误的标记校正器

http://www.crummy.com/software/BeautifulSoup/

于 2011-02-13T17:14:11.870 回答
0

我最初的想法是使用 XML 解析器(可能是 python 的 sax 解析器),然后可能计算每个 xml 元素中的文本字符。我会忽略标签字符数以使其更一致和更简单,但两者都应该是可能的。

于 2011-02-11T15:13:01.917 回答
0

我建议首先完全解析 HTML 然后截断。python 的一个很棒的 HTML 解析器是lxml。解析和截断后,您可以将其打印回 HTML 格式。

于 2011-02-11T15:14:24.627 回答
0

查看HTML Tidy以清理/重新格式化/重新缩进 HTML。

于 2011-02-11T18:52:12.693 回答