python基础教程项目四之新闻聚合


Posted in Python onApril 02, 2018

《python基础教程》书中的第四个练习,新闻聚合。现在很少见的一类应用,至少我从来没有用过,又叫做Usenet。这个程序的主要功能是用来从指定的来源(这里是Usenet新闻组)收集信息,然后讲这些信息保存到指定的目的文件中(这里使用了两种形式:纯文本和html文件)。这个程序的用处有些类似于现在的博客订阅工具或者叫RSS订阅器。

先上代码,然后再来逐一分析:

from nntplib import NNTP
from time import strftime,time,localtime
from email import message_from_string
from urllib import urlopen
import textwrap
import re
day = 24*60*60
def wrap(string,max=70):
    '''
    '''
    return '\n'.join(textwrap.wrap(string)) + '\n'
class NewsAgent:
    '''
    '''
    def __init__(self):
        self.sources = []
        self.destinations = []
    def addSource(self,source):
        self.sources.append(source)
    def addDestination(self,dest):
        self.destinations.append(dest)
    def distribute(self):
        items = []
        for source in self.sources:
            items.extend(source.getItems())
        for dest in self.destinations:
            dest.receiveItems(items)
class NewsItem:
    def __init__(self,title,body):
        self.title = title
        self.body = body
class NNTPSource:
    def __init__(self,servername,group,window):
        self.servername = servername
        self.group = group
        self.window = window
    def getItems(self):
        start = localtime(time() - self.window*day)
        date = strftime('%y%m%d',start)
        hour = strftime('%H%M%S',start)
        server = NNTP(self.servername)
        ids = server.newnews(self.group,date,hour)[1]
        for id in ids:
            lines = server.article(id)[3]
            message = message_from_string('\n'.join(lines))
            title = message['subject']
            body = message.get_payload()
            if message.is_multipart():
                body = body[0]
            yield NewsItem(title,body)
        server.quit()
class SimpleWebSource:
    def __init__(self,url,titlePattern,bodyPattern):
        self.url = url
        self.titlePattern = re.compile(titlePattern)
        self.bodyPattern = re.compile(bodyPattern)
    def getItems(self):
        text = urlopen(self.url).read()
        titles = self.titlePattern.findall(text)
        bodies = self.bodyPattern.findall(text)
        for title.body in zip(titles,bodies):
            yield NewsItem(title,wrap(body))
class PlainDestination:
    def receiveItems(self,items):
        for item in items:
            print item.title
            print '-'*len(item.title)
            print item.body
class HTMLDestination:
    def __init__(self,filename):
        self.filename = filename
    def receiveItems(self,items):
        out = open(self.filename,'w')
        print >> out,'''
        <html>
        <head>
         <title>Today's News</title>
        </head>
        <body>
        <h1>Today's News</hi>
        '''
        print >> out, '<ul>'
        id = 0
        for item in items:
            id += 1
            print >> out, '<li><a href="#" rel="external nofollow" >%s</a></li>' % (id,item.title)
        print >> out, '</ul>'
        id = 0
        for item in items:
            id += 1
            print >> out, '<h2><a name="%i">%s</a></h2>' % (id,item.title)
            print >> out, '<pre>%s</pre>' % item.body
        print >> out, '''
        </body>
        </html>
        '''
def runDefaultSetup():
    agent = NewsAgent()
    bbc_url = 'http://news.bbc.co.uk/text_only.stm'
    bbc_title = r'(?s)a href="[^" rel="external nofollow" ]*">\s*<b>\s*(.*?)\s*</b>'
    bbc_body = r'(?s)</a>\s*<br/>\s*(.*?)\s*<'
    bbc = SimpleWebSource(bbc_url, bbc_title, bbc_body)
    agent.addSource(bbc)
    clpa_server = 'news2.neva.ru'
    clpa_group = 'alt.sex.telephone'
    clpa_window = 1
    clpa = NNTPSource(clpa_server,clpa_group,clpa_window)
    agent.addSource(clpa)
    agent.addDestination(PlainDestination())
    agent.addDestination(HTMLDestination('news.html'))
    agent.distribute()
if __name__ == '__main__':
    runDefaultSetup()

这个程序,首先从整体上进行分析,重点部分在于NewsAgent,它的作用是存储新闻来源,存储目标地址,然后在分别调用来源服务器(NNTPSource以及SimpleWebSource)以及写新闻的类(PlainDestination和HTMLDestination)。所以从这里也看的出,NNTPSource是专门用来获取新闻服务器上的信息的,SimpleWebSource是获取一个url上的数据的。而PlainDestination和HTMLDestination的作用很明显,前者是用来输出获取到的内容到终端的,后者是写数据到html文件中的。

有了这些分析,然后在来看主程序中的内容,主程序就是来给NewsAgent添加信息源和输出目的地址的。

这确实是个简单的程序,不过这个程序可是用到了分层了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python挑选文件夹里宽大于300图片的方法
Mar 05 Python
Python中的多重装饰器
Apr 11 Python
python如何实现数据的线性拟合
Jul 19 Python
简单了解python协程的相关知识
Aug 31 Python
基于python进行抽样分布描述及实践详解
Sep 02 Python
python SVD压缩图像的实现代码
Nov 05 Python
Python unittest工作原理和使用过程解析
Feb 24 Python
python实现简单俄罗斯方块
Mar 13 Python
Python之Matplotlib文字与注释的使用方法
Jun 18 Python
Python库安装速度过慢解决方案
Jul 14 Python
torchxrayvision包安装过程(附pytorch1.6cpu版安装)
Aug 26 Python
Python 的 __str__ 和 __repr__ 方法对比
Sep 02 Python
Python实现将数据框数据写入mongodb及mysql数据库的方法
Apr 02 #Python
python基础教程项目三之万能的XML
Apr 02 #Python
python opencv检测目标颜色的实例讲解
Apr 02 #Python
浅谈python配置与使用OpenCV踩的一些坑
Apr 02 #Python
python基础教程项目二之画幅好画
Apr 02 #Python
通过Python 接口使用OpenCV的方法
Apr 02 #Python
Python 3.x 安装opencv+opencv_contrib的操作方法
Apr 02 #Python
You might like
用PHP连接Oracle数据库
2006/10/09 PHP
PHP Zip压缩 在线对文件进行压缩的函数
2010/05/26 PHP
8个出色的WordPress SEO插件收集
2011/02/26 PHP
Ajax提交表单时验证码自动验证 php后端验证码检测
2016/07/20 PHP
thinkphp自定义权限管理之名称判断方法
2017/04/01 PHP
Firebug入门指南(Firefox浏览器)
2010/08/21 Javascript
深入理解JavaScript系列(6) 强大的原型和原型链
2012/01/15 Javascript
关于JS控制代码暂停的实现方法分享
2012/10/11 Javascript
浅析jQuery1.8的几个小变化
2013/12/10 Javascript
深入理解JavaScript系列(31):设计模式之代理模式详解
2015/03/03 Javascript
JavaScript中有关一个数组中最大值和最小值及它们的下表的输出的解决办法
2016/07/01 Javascript
Javascript中八种遍历方法的执行速度深度对比
2017/04/25 Javascript
React Native时间转换格式工具类分享
2017/10/24 Javascript
JS 中document.write()的用法和清空的原因浅析
2017/12/04 Javascript
vue中的$emit 与$on父子组件与兄弟组件的之间通信方式
2018/05/13 Javascript
react实现点击选中的li高亮的示例代码
2018/05/24 Javascript
webpack打包react项目的实现方法
2018/06/21 Javascript
Angular6 Filter实现页面搜索的示例代码
2018/12/02 Javascript
JS中创建自定义类型的常用模式总结【工厂模式,构造函数模式,原型模式,动态原型模式等】
2019/01/19 Javascript
使用React手写一个对话框或模态框的方法示例
2019/04/25 Javascript
基于python的汉字转GBK码实现代码
2012/02/19 Python
pygame学习笔记(3):运动速率、时间、事件、文字
2015/04/15 Python
python实现中文转换url编码的方法
2016/06/14 Python
简单实现python数独游戏
2018/03/30 Python
DataFrame 将某列数据转为数组的方法
2018/04/13 Python
对python for 文件指定行读写操作详解
2018/12/29 Python
超实用的 30 段 Python 案例
2019/10/10 Python
使用python创建生成动态链接库dll的方法
2020/05/09 Python
基于Python词云分析政府工作报告关键词
2020/06/02 Python
Keras 使用 Lambda层详解
2020/06/10 Python
详解canvas绘制网络字体几种方法
2019/08/27 HTML / CSS
使用iframe+postMessage实现页面跨域通信的示例代码
2020/01/14 HTML / CSS
德国童装购物网站:NICKI´S.com
2018/04/20 全球购物
债务追讨授权委托书范本
2014/10/16 职场文书
2014年科室工作总结
2014/11/20 职场文书
Python自然语言处理之切分算法详解
2021/04/25 Python