NNTP:网络新闻传输协议,Network News Transfer Protocol

目标:  

  从多种不同的来源收集新闻;

  用户可以轻松添加新的新闻来源(甚至是新类型的新闻来源;

  程序可以将编译好的新闻报告分派出多个不同格式的目标;

  程序可以轻松添加新的目标(甚至是新种类的目标)

1. 简单的新闻代理程序

1)NNTP类对象:使用NNTP服务器名字实例化;

      newnews方法: 返回给定日期时间之后发布的文章;

    head方法:提供关于文件(主要是主题)的各种信息;  

    body方法:提供文章的正文文本

2)time.localtime([ sec ])   : 将秒数sec转换为time.struct_time类型的对象

   time.strftime(format[, t])  : format -- 格式字符串,   t -- 可选的参数t是一个struct_time对象      返回以可读字符串表示的时间

#newsagent1.py
from nntplib import NNTP
from time import strftime, time, localtime day=24*60*60
yesterday=localtime(time()-day)
date=strftime('%y%m%d', yesterday)
hour=strftime('%H%M%S', yesterday) servername='news.foo.bar' #虚构的服务器名
group='comp.lang.python.announce'
sever=NNTP(servername) ids=server.newnews(group.date.hour)[1] #提取newnews方法返回元组的第二个参数,即发表文章的ID号 for id in ids:
head=server.head(id)[3] #返回信息元组的第四个元素:字符串列表(数据本身)
for line in head:
if line.lower().startswitch('subject:'):
subject= line[9:]
break body=server.body(id)[3] print subject
print '-'*len(subject)
print '\n'.join(body) server.quit()

2. 改进

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:
'''
从NNTP组中获取新闻项目的新闻来源
'''
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:
'''
将所有的新闻项目格式化为HTML的目标类
'''
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="#">%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() '''
从BBS新闻站获取新闻的SimpleWebSource
'''
bbc_url = 'http://news.bbc.co.uk/text_only.stm'
bbc_title = r'(?s)a href="[^"]*">\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) '''
从comp.lang.python.announce获取新闻的NNTPSource
'''
clpa_server = 'news2.neva.ru'
clpa_group = 'alt.sex.telephone'
clpa_window = 1
clpa = NNTPSource(clpa_server,clpa_group,clpa_window) agent.addSource(clpa) '''
增加纯文本目标和HTML目标
'''
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基础教程总结15——4 新闻聚合的更多相关文章

  1. python基础教程总结15——7 自定义电子公告板

    1. Python进行SQLite数据库操作 简单的介绍 SQLite数据库是一款非常小巧的嵌入式开源数据库软件,也就是说没有独立的维护进程,所有的维护都来自于程序本身.它是遵守ACID的关联式数据库 ...

  2. python基础教程总结15——6 CGI远程编辑

    功能: 将文档作为普通网页显示: 在web表单的文本域内显示文档: 保存表单中的文本: 使用密码保护文档: 容易拓展,支持处理多余一个文档的情况 1.CGI CGI(Comment Gateway I ...

  3. python基础教程总结15——5 虚拟茶话会

    聊天服务器: 服务器能接受来自不同用户的多个连接: 允许用户同时(并行)操作: 能解释命令,例如,say或者logout: 容易拓展 套接字和端口: 套接字是一种使用标准UNIX文件描述符(file ...

  4. python基础教程总结15——3 XML构建网址

    要求: 网址用一个XML文件描述,其中包括独立网页和目录的信息: 程序能创建所需的目录和网页: 可以改变网址的设计,并且以新的设计为基础重新生成所有网页 概念: 网站:不用存储有关网站本身的任何信息, ...

  5. python基础教程总结15——1.即时标记

    1. 测试文档: # test_input.txt Welcome to World Wide Spam. Inc. These are the corporate web pages of *Wor ...

  6. python基础教程总结15——2 画幅好画

    要求:从Internet上下载数据文件:  分析数据文件并提取感兴趣的部分 工具:图形生成包(ReportLab,PYX等) 数据:太阳黑子和射电辐射流量(http://services.swpc.n ...

  7. Python基础教程(第2版 修订版) pdf

    Python基础教程(第2版 修订版) 目录 D11章快速改造:基础知识11.1安装Python11.1.1Windows11.1.2Linux和UNIX31.1.3苹果机(Macintosh)41. ...

  8. Python基础教程(第3版)PDF高清完整版免费下载|百度云盘

    百度云盘:Python基础教程(第3版)PDF高清完整版免费下载 提取码:gkiy 内容简介 本书包括Python程序设计的方方面面:首先从Python的安装开始,随后介绍了Python的基础知识和基 ...

  9. Python 基础教程 —— Pandas 库常用方法实例说明

    目录 1. 常用方法 pandas.Series 2. pandas.DataFrame ([data],[index])   根据行建立数据 3. pandas.DataFrame ({dic})  ...

随机推荐

  1. ZOJ 2671 Cryptography 矩阵乘法+线段树

    B - Cryptography Time Limit:5000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu Subm ...

  2. JavaWeb_tomcat设置默认应用

    在tomcat的server.xml文件中设置默认应用. 在tomcat文件目录里面的conf/server.xml文件中,在<Engine>...</Engine>中再增加一 ...

  3. Consuming JSON Strings in SQL Server

    https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/ Consuming JS ...

  4. 一次偶然的点开一盏灯引发的SEO初识

    事情是这样,不小心点开了dev tools的审计(audits)面板,点开了灯之后,画风如下 emmm, SEO 跑了满分也,好奇宝宝就往下滚到SEO区域,发现了如下新大陆 嗯,原来是应用满足了打钩的 ...

  5. Keras实现MNIST分类

      仅仅为了学习Keras的使用,使用一个四层的全连接网络对MNIST数据集进行分类,网络模型各层结点数为:784: 256: 128 : 10:   使用整体数据集的75%作为训练集,25%作为测试 ...

  6. poj2449(k短路&A_star模板)

    题目链接:http://poj.org/problem?id=2449 题意:给出一个有向图,求s到t的第k短路: 思路:k短路模板题,可以用A_star模板过: 单源点最短路径+高级搜索A*;A*算 ...

  7. 跟踪记录ABAP对外部系统的RFC通信

    对SAP系统而言,RFC最常见的系统间通信方式,SAP与SAP系统及SAP与非SAP系统之间的连接都可以使用它.它的使用便利,功能强大,在各种接口技术中,往往是最受(ABAP开发者)青睐的选择. 查询 ...

  8. Codeforces 185D(发现性质、欧拉定理)

    学到的东西 不知道gcd时不妨先假设为d,然后为了满足全部式子说不定可以得到d的取值范围. 幂上带幂考虑欧拉定理的使用. 有几个特殊情况会破坏公式的完美不要紧,看看特殊情况是否能简便地判定. 连乘公式 ...

  9. CodeForces - 508B-Anton and currency you all know

    Berland, 2016. The exchange rate of currency you all know against the burle has increased so much th ...

  10. 关系型数据库---MySQL---数据表

    1.在创建一个新的MySQL数据表时,可以为它设置一个类型: 2.MySQL支持多种数据表类型,有各自的特点和属性,最重要的3种类型: 1.1 MyISAM 1.2 InnoDB 1.1 可以把Inn ...