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


Posted in Python onApril 21, 2015

本文实例讲述了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程序设计有所帮助。

Python 相关文章推荐
python绘图库Matplotlib的安装
Jul 03 Python
Python实现合并字典的方法
Jul 07 Python
python无限生成不重复(字母,数字,字符)组合的方法
Dec 04 Python
python tkinter实现界面切换的示例代码
Jun 14 Python
Pycharm保存不能自动同步到远程服务器的解决方法
Jun 27 Python
Pytorch 抽取vgg各层并进行定制化处理的方法
Aug 20 Python
Python多个装饰器的调用顺序实例解析
May 22 Python
Python文件操作模拟用户登陆代码实例
Jun 09 Python
Python为何不支持switch语句原理详解
Oct 21 Python
Python request post上传文件常见要点
Nov 20 Python
Python 详解通过Scrapy框架实现爬取百度新冠疫情数据流程
Nov 11 Python
python计算列表元素与乘积详情
Aug 05 Python
python中map、any、all函数用法分析
Apr 21 #Python
用于统计项目中代码总行数的Python脚本分享
Apr 21 #Python
Python中实现参数类型检查的简单方法
Apr 21 #Python
python实现的jpg格式图片修复代码
Apr 21 #Python
在Python的Flask框架中使用日期和时间的教程
Apr 21 #Python
在Python的Flask框架下收发电子邮件的教程
Apr 21 #Python
在Python的Flask框架中实现全文搜索功能
Apr 20 #Python
You might like
8个出色的WordPress SEO插件收集
2011/02/26 PHP
php使用ffmpeg向视频中添加文字字幕的实现方法
2016/05/23 PHP
thinkphp中U方法按路由规则生成url的方法
2018/03/12 PHP
jQuery学习笔记之控制页面实现代码
2012/02/27 Javascript
javascript获取浏览器类型和版本的方法(js获取浏览器版本)
2014/03/13 Javascript
jQuery中[attribute^=value]选择器用法实例
2014/12/31 Javascript
jQuery实现购物车表单自动结算效果实例
2015/08/10 Javascript
Jquery轮播效果实现过程解析
2016/03/30 Javascript
Ionic2系列之使用DeepLinker实现指定页面URL
2016/11/21 Javascript
Vue2.x中的Render函数详解
2017/05/30 Javascript
Vue函数式组件-你值得拥有
2019/05/09 Javascript
Vue表单绑定的实例代码(单选按钮,选择框(单选时,多选时,用 v-for 渲染的动态选项)
2019/05/13 Javascript
JavaScript动态检测密码强度原理及实现方法详解
2019/06/11 Javascript
layui动态渲染生成左侧3级菜单的方法(根据后台返回数据)
2019/09/23 Javascript
Vue中rem与postcss-pxtorem的应用详解
2019/11/20 Javascript
在博客园博文中添加自定义右键菜单的方法详解
2020/02/05 Javascript
详解vue高级特性
2020/06/09 Javascript
使用Python的Flask框架表单插件Flask-WTF实现Web登录验证
2016/07/12 Python
python 删除大文件中的某一行(最有效率的方法)
2017/08/19 Python
使用python和Django完成博客数据库的迁移方法
2018/01/05 Python
python实现决策树ID3算法的示例代码
2018/05/30 Python
Python动态导入模块:__import__、importlib、动态导入的使用场景实例分析
2020/03/30 Python
plt.figure()参数使用详解及运行演示
2021/01/08 Python
css3进行截取替代js的substring
2013/09/02 HTML / CSS
美国运动鞋类和服装零售连锁店:Shoe Palace
2019/08/13 全球购物
Ray-Ban雷朋太阳眼镜英国官网:Ray-Ban UK
2019/11/23 全球购物
购房协议书
2014/04/11 职场文书
工伤事故赔偿协议书
2014/04/15 职场文书
在校大学生自我评价范文
2014/09/12 职场文书
2014党的群众路线教育实践活动总结材料
2014/10/31 职场文书
2014年扫黄打非工作总结
2014/12/03 职场文书
离婚撤诉申请书范本
2015/05/18 职场文书
小学校本教研总结
2015/08/13 职场文书
创新创业项目计划书该怎样写?
2019/08/13 职场文书
创业计划书之游泳馆
2019/09/16 职场文书
实战 快速定位MySQL的慢SQL
2022/03/22 MySQL