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

yipeiwu_com5年前Python基础

本文实例讲述了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 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摘要提取功能,其实有更简洁的实现方案(相比 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程序设计有所帮助。

相关文章

浅谈function(函数)中的动态参数

我们可向函数传递动态参数,*args,**kwargs,首先我们来看*args,示例如下: 1.show(*args) def show(*args): print(args,typ...

8种用Python实现线性回归的方法对比详解

8种用Python实现线性回归的方法对比详解

前言 说到如何用Python执行线性回归,大部分人会立刻想到用sklearn的linear_model,但事实是,Python至少有8种执行线性回归的方法,sklearn并不是最高效的。...

python读取json文件并将数据插入到mongodb的方法

本文实例讲述了python读取json文件并将数据插入到mongodb的方法。分享给大家供大家参考。具体实现方法如下: #coding=utf-8 import sunburnt i...

django 数据库连接模块解析及简单长连接改造方法

工作中纯服务端的项目用到了线程池和django的ORM部分。django 的数据库连接在每一个线程中开启一份,并在查询完毕后自动关闭连接。 线程池处理任务时,正常使用的连接中不会被关闭,...

基于Python的身份证号码自动生成程序

基于Python的身份证号码自动生成程序

需求细化: 1.身份证必须能够通过身份证校验程序。 2.通过查询,发现身份证号码是有国家标准的,标准号为 GB 11643-1999 可以从百度下载到这个文档 下载:GB11643-19...