【PYTHON教程】提取文章摘要
在博客系统的文章列表中,为了更有效地呈现文章内容,从而让读者更有针对性地选择阅读,通常会同时提供文章的标题和摘要。
一篇文章的内容可以是纯文本格式的,但在网络盛行的当今,更多是HTML格式的。无论是哪种格式,摘要一般都是文章开头部分的内容,可以按照指定的字数来提取。
纯文本摘要
首先我们对纯文本摘要进行提取,纯文本文档就是一个长字符串,很容易实现对它的摘要提取:
#!/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 doctestdoctest.testmod()
HTML摘要
立即学习“Python免费学习笔记(深入)”;
HTML文档中包含大量标记符(如
、
、等等),这些字符都是标记指令,并且通常是成对出现的,简单的文本截取会破坏HTML的文档结构,进而导致摘要在浏览器中显示不当。
在遵循HTML文档结构的同时,又要对内容进行截取,就需要解析HTML文档。在Python中,可以借助标准库HTMLParser来完成。
一个最简单的摘要提取功能,是忽略HTML标记符而只提取标记内部的原生文本。以下就是类似该功能的Python实现:
#!/usr/bin/env python# -*- coding: utf-8 -*-"""Get a raw summary of the HTML-format document"""from HTMLParser import HTMLParserclass 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 = countself.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'{1}{2}{0}>'.format(wrapper, self.summary, suffix)if __name__ == '__main__':import doctestdoctest.testmod()