python基础教程总结15——4 新闻聚合
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 新闻聚合的更多相关文章
- python基础教程总结15——7 自定义电子公告板
1. Python进行SQLite数据库操作 简单的介绍 SQLite数据库是一款非常小巧的嵌入式开源数据库软件,也就是说没有独立的维护进程,所有的维护都来自于程序本身.它是遵守ACID的关联式数据库 ...
- python基础教程总结15——6 CGI远程编辑
功能: 将文档作为普通网页显示: 在web表单的文本域内显示文档: 保存表单中的文本: 使用密码保护文档: 容易拓展,支持处理多余一个文档的情况 1.CGI CGI(Comment Gateway I ...
- python基础教程总结15——5 虚拟茶话会
聊天服务器: 服务器能接受来自不同用户的多个连接: 允许用户同时(并行)操作: 能解释命令,例如,say或者logout: 容易拓展 套接字和端口: 套接字是一种使用标准UNIX文件描述符(file ...
- python基础教程总结15——3 XML构建网址
要求: 网址用一个XML文件描述,其中包括独立网页和目录的信息: 程序能创建所需的目录和网页: 可以改变网址的设计,并且以新的设计为基础重新生成所有网页 概念: 网站:不用存储有关网站本身的任何信息, ...
- python基础教程总结15——1.即时标记
1. 测试文档: # test_input.txt Welcome to World Wide Spam. Inc. These are the corporate web pages of *Wor ...
- python基础教程总结15——2 画幅好画
要求:从Internet上下载数据文件: 分析数据文件并提取感兴趣的部分 工具:图形生成包(ReportLab,PYX等) 数据:太阳黑子和射电辐射流量(http://services.swpc.n ...
- Python基础教程(第2版 修订版) pdf
Python基础教程(第2版 修订版) 目录 D11章快速改造:基础知识11.1安装Python11.1.1Windows11.1.2Linux和UNIX31.1.3苹果机(Macintosh)41. ...
- Python基础教程(第3版)PDF高清完整版免费下载|百度云盘
百度云盘:Python基础教程(第3版)PDF高清完整版免费下载 提取码:gkiy 内容简介 本书包括Python程序设计的方方面面:首先从Python的安装开始,随后介绍了Python的基础知识和基 ...
- Python 基础教程 —— Pandas 库常用方法实例说明
目录 1. 常用方法 pandas.Series 2. pandas.DataFrame ([data],[index]) 根据行建立数据 3. pandas.DataFrame ({dic}) ...
随机推荐
- Spring入门第十九课
后置通知 看代码: package logan.study.aop.impl; public interface ArithmeticCalculator { int add(int i, int j ...
- iOS内购流程一(协议、税务和银行业务)
协议.税务和银行业务,这一选项是当你App使用了In-app purchaes时候,你跟苹果签订协议的,需要签订合同和填写你的银行收款等信息 一.填写法人信息 1.登录iTunes Store,点击协 ...
- 苦逼三流小公司程序员这半年找工作经历(3)——选择offer
本文按照企业规模.性质.规模,分成三类,点评一下遇到的这些公司.也算是为半年找工作经历的一个总结. 1,三流小公司 公司规模类似于笔者跳槽前所在企业,性质有外商独资.合资,当然大多数都是民营企业,规模 ...
- nginx 初了解
随着现代web开发的发展,restful,前后端分离,前端js框架的应用越来越普遍.很多web应用请求的接口可能根本就存在于不同的服务器,类似于微信,支付宝等等.这其中就会存在跨域的问题.简单来说,跨 ...
- 洛谷P2292 [HNOI2004]L语言
传送门 建好trie树 当$dp[j]==1$当且仅当存在$dp[k]=1$且$T[k+1,j]==word[i]$ 然后乱搞就行了 //minamoto #include<iostream&g ...
- MySQL学习基础之一 — 数据库查询
廖大神的练手神器:在线SQL: https://www.liaoxuefeng.com/wiki/1177760294764384/1179611432985088 运行MySQL等实际的数据库软件, ...
- maven工程运行出Unable to compile class for JSP: 错误
使用mvn tomcat:run运行时出现500错误,使用tomcat7再次运行就好了 更新,上面的是在命令行操作的 如果要在idea上面出现错误的话需要在pom.xml上配置下面的语句 org.ap ...
- java基础第八篇之jdk1.5、jdk1.7、jdk1.8新特性
JDK5新特性 自动装箱和拆箱 泛型 增强for循环 静态导入 可变参数 枚举 枚举概述 是指将变量的值一一列出来,变量的值只限于列举出来的值的范围内.举例:一周只有7天,一年只有12个月等. 回想单 ...
- Codeforces 1C(外接圆与正多边形)
要点 各点肯定都在外接圆上,边越多越接近圆面积,所以要最小面积应当取可能的最少边数. 给三角形求外接圆半径公式:\(R=\frac{abc}{4S}\). 三个角度对应的圆心角取gcd即是要求的正多边 ...
- CodeForces - 287B-Pipeline(二分)
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ult ...