Python實踐:提取文章摘要

1、概述

在博客系統的文章列表中,爲了更有效地呈現文章內容,從而讓讀者更有針對性地選擇閱讀,一般會同時提供文章的標題和摘要。html

一篇文章的內容能夠是純文本格式的,但在網絡盛行的當今,更可能是HTML格式的。不管是哪一種格式,摘要 通常都是文章 開頭部分 的內容,能夠按照指定的 字數 來提取。python

2、純文本摘要

純文本文檔 就是一個長字符串,很容易實現對它的摘要提取:瀏覽器

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Get a summary of the TEXT-format document"""

def get_summary(text, count):
    u"""Get the first `count` characters from `text`

        >>> text = u'Welcome 這是一篇關於Python的文章'
        >>> get_summary(text, 12) == u'Welcome 這是一篇'
        True
    """
    assert(isinstance(text, unicode))
    return text[0:count]

if __name__ == '__main__':
    import doctest
    doctest.testmod()

3、HTML摘要

HTML文檔 中包含大量標記符(如&lth1>、&ltp>、&lta&gt等等),這些字符都是標記指令,而且一般是成對出現的,簡單的文本截取會破壞HTML的文檔結構,進而致使摘要在瀏覽器中顯示不當。markdown

在遵循HTML文檔結構的同時,又要對內容進行截取,就須要解析HTML文檔。在Python中,能夠藉助標準庫 HTMLParser 來完成。網絡

一個最簡單的摘要提取功能,是忽略HTML標記符而只提取標記內部的原生文本。若是您不明白我說的意思,能夠看看 博客園 的摘要功能,如下就是相似該功能的Python實現:app

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Get a raw summary of the HTML-format document"""

from HTMLParser import HTMLParser

class SummaryHTMLParser(HTMLParser):
    """Parse HTML text to get a summary

        >>> text = u'<p>Hi guys:</p><p>This is a example using SummaryHTMLParser.</p>'
        >>> parser = SummaryHTMLParser(10)
        >>> parser.feed(text)
        >>> parser.get_summary(u'...')
        u'<p>Higuys:Thi...</p>'
    """
    def __init__(self, count):
        HTMLParser.__init__(self)
        self.count = count
        self.summary = u''

    def feed(self, data):
        """Only accept unicode `data`"""
        assert(isinstance(data, unicode))
        HTMLParser.feed(self, data)

    def handle_data(self, data):
        more = self.count - len(self.summary)
        if more > 0:
            # Remove possible whitespaces in `data`
            data_without_whitespace = u''.join(data.split())

            self.summary += data_without_whitespace[0:more]

    def get_summary(self, suffix=u'', wrapper=u'p'):
        return u'<{0}>{1}{2}</{0}>'.format(wrapper, self.summary, suffix)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

========== 更新 ==========spa

HTMLParser(或者 BeautifulSoup 等等)更適合完成複雜的HTML摘要提取功能,對於上述簡單的HTML摘要提取功能,其實有更簡潔的實現方案(相比 SummaryHTMLParser 而言):code

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Get a raw summary of the HTML-format document"""

import re

def get_summary(text, count, suffix=u'', wrapper=u'p'):
    """A simpler implementation (vs `SummaryHTMLParser`).

        >>> text = u'<p>Hi guys:</p><p>This is a example using SummaryHTMLParser.</p>'
        >>> get_summary(text, 10, u'...')
        u'<p>Higuys:Thi...</p>'
    """
    assert(isinstance(text, unicode))
    summary = re.sub(r'<.*?>', u'', text) # key difference: use regex
    summary = u''.join(summary.split())[0:count]
    return u'<{0}>{1}{2}</{0}>'.format(wrapper, summary, suffix)

if __name__ == '__main__':
    import doctest
    doctest.testmod()
相關文章
相關標籤/搜索