您好,欢迎访问一九零五行业门户网

Python实现提取文章摘要的方法

本文实例讲述了python实现提取文章摘要的方法。分享给大家供大家参考。具体如下:
一、概述
在博客系统的文章列表中,为了更有效地呈现文章内容,从而让读者更有针对性地选择阅读,通常会同时提供文章的标题和摘要。
一篇文章的内容可以是纯文本格式的,但在网络盛行的当今,更多是html格式的。无论是哪种格式,摘要 一般都是文章 开头部分 的内容,可以按照指定的 字数 来提取。
二、纯文本摘要
纯文本文档 就是一个长字符串,很容易实现对它的摘要提取:
#!/usr/bin/env python# -*- coding: utf-8 -*-get a summary of the text-format documentdef get_summary(text, count): uget 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()
三、html摘要
html文档 中包含大量标记符(如、、等等),这些字符都是标记指令,并且通常是成对出现的,简单的文本截取会破坏html的文档结构,进而导致摘要在浏览器中显示不当。
在遵循html文档结构的同时,又要对内容进行截取,就需要解析html文档。在python中,可以借助标准库 htmlparser 来完成。
一个最简单的摘要提取功能,是忽略html标记符而只提取标记内部的原生文本。以下就是类似该功能的python实现:
#!/usr/bin/env python# -*- coding: utf-8 -*-get a raw summary of the html-format documentfrom htmlparser import htmlparserclass summaryhtmlparser(htmlparser): parse html text to get a summary >>> text = u'hi guys:
this is a example using summaryhtmlparser.
' >>> parser = summaryhtmlparser(10) >>> parser.feed(text) >>> parser.get_summary(u'...') u'higuys:thi...
' 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'{1}{2}'.format(wrapper, self.summary, suffix)if __name__ == '__main__': import doctest doctest.testmod()
htmlparser(或者 beautifulsoup 等等)更适合完成复杂的html摘要提取功能,对于上述简单的html摘要提取功能,其实有更简洁的实现方案(相比 summaryhtmlparser 而言):
#!/usr/bin/env python# -*- coding: utf-8 -*-get a raw summary of the html-format documentimport redef get_summary(text, count, suffix=u'', wrapper=u'p'): a simpler implementation (vs `summaryhtmlparser`). >>> text = u'hi guys:
this is a example using summaryhtmlparser.
' >>> get_summary(text, 10, u'...') u'higuys:thi...
' assert(isinstance(text, unicode)) summary = re.sub(r'', u'', text) # key difference: use regex summary = u''.join(summary.split())[0:count] return u'{1}{2}'.format(wrapper, summary, suffix)if __name__ == '__main__': import doctest doctest.testmod()
希望本文所述对大家的python程序设计有所帮助。
其它类似信息

推荐信息