一篇文章的內(nèi)容可以是純文本格式的,但在網(wǎng)絡盛行的當今,更多是HTML格式的。無論是哪種格式,摘要一般都是文章開頭部分的內(nèi)容,可以按照指定的字數(shù)來提取。
純文本摘要
首先我們對純文本摘要進行提取,純文本文檔就是一個長字符串,很容易實現(xiàn)對它的摘要提?。?/p>
#!/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()
HTML摘要
HTML文檔中包含大量標記符(如<h1>、<p>、<a>等等),這些字符都是標記指令,并且通常是成對出現(xiàn)的,簡單的文本截取會破壞HTML的文檔結構,進而導致摘要在瀏覽器中顯示不當。
在遵循HTML文檔結構的同時,又要對內(nèi)容進行截取,就需要解析HTML文檔。在Python中,可以借助標準庫HTMLParser來完成。
一個最簡單的摘要提取功能,是忽略HTML標記符而只提取標記內(nèi)部的原生文本。以下就是類似該功能的Python實現(xiàn):
#!/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()
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com