Python實現(xiàn)提取文章摘要的方法
本文實例講述了Python實現(xiàn)提取文章摘要的方法。分享給大家供大家參考。具體如下:
一、概述
在博客系統(tǒng)的文章列表中,為了更有效地呈現(xiàn)文章內容,從而讓讀者更有針對性地選擇閱讀,通常會同時提供文章的標題和摘要。
一篇文章的內容可以是純文本格式的,但在網(wǎng)絡盛行的當今,更多是HTML格式的。無論是哪種格式,摘要 一般都是文章 開頭部分 的內容,可以按照指定的 字數(shù) 來提取。
二、純文本摘要
純文本文檔 就是一個長字符串,很容易實現(xiàn)對它的摘要提取:
#!/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文檔結構的同時,又要對內容進行截取,就需要解析HTML文檔。在Python中,可以借助標準庫 HTMLParser 來完成。
一個最簡單的摘要提取功能,是忽略HTML標記符而只提取標記內部的原生文本。以下就是類似該功能的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()
HTMLParser(或者 BeautifulSoup 等等)更適合完成復雜的HTML摘要提取功能,對于上述簡單的HTML摘要提取功能,其實有更簡潔的實現(xiàn)方案(相比 SummaryHTMLParser 而言):
#!/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()
希望本文所述對大家的Python程序設計有所幫助。
相關文章
pyqt彈出新對話框,以及關閉對話框獲取數(shù)據(jù)的實例
今天小編就為大家分享一篇pyqt彈出新對話框,以及關閉對話框獲取數(shù)據(jù)的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python判斷遠程服務器上Excel文件是否被人打開的方法
這篇文章主要介紹了Python如何判斷遠程服務器上Excel文件是否被人打開,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
Python?matplotlib.pyplot.subplots()用法詳解
這篇文章主要介紹了Python?matplotlib.pyplot.subplots()用法的相關資料,matplotlib.pyplot.subplots()用于創(chuàng)建子圖,可設置行數(shù)、列數(shù)、軸共享、額外關鍵字參數(shù)和布局選項,需要的朋友可以參考下2024-12-12

