国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現提取文章摘要的方法

2020-01-04 19:26:51
字體:
來源:轉載
供稿:網友

本文實例講述了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 doctest doctest.testmod()

三、HTML摘要

HTML文檔 中包含大量標記符(如<h1>、<p>、<a>等等),這些字符都是標記指令,并且通常是成對出現的,簡單的文本截取會破壞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'<{0}>{1}{2}</{0}>'.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 document"""import redef 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()

希望本文所述對大家的Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁安市| 九龙县| 云浮市| 济南市| 都江堰市| 葫芦岛市| 巢湖市| 延寿县| 镶黄旗| 曲靖市| 博野县| 吉安县| 富顺县| 通州区| 怀宁县| 诏安县| 沂水县| 浪卡子县| 普格县| 淅川县| 屏东市| 宝清县| 托克托县| 会理县| 栾川县| 恭城| 拉萨市| 简阳市| 石家庄市| 井研县| 呼和浩特市| 白玉县| 津市市| 武胜县| 龙州县| 章丘市| 辰溪县| 贵港市| 嘉祥县| 洛浦县| 交城县|