欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實現(xiàn)提取文章摘要的方法

 更新時間:2015年04月21日 16:27:38   作者:RussellLuo  
這篇文章主要介紹了Python實現(xiàn)提取文章摘要的方法,實例分析了Python提取文章摘要的原理與實現(xiàn)技巧,需要的朋友可以參考下

本文實例講述了Python實現(xiàn)提取文章摘要的方法。分享給大家供大家參考。具體如下:

一、概述

在博客系統(tǒng)的文章列表中,為了更有效地呈現(xiàn)文章內(nèi)容,從而讓讀者更有針對性地選擇閱讀,通常會同時提供文章的標題和摘要。

一篇文章的內(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 這是一篇關(guān)于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的文檔結(jié)構(gòu),進而導致摘要在瀏覽器中顯示不當。

在遵循HTML文檔結(jié)構(gòu)的同時,又要對內(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()

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程序設計有所幫助。

相關(guān)文章

最新評論