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}) ...
随机推荐
- LeetCode: 383 Ransom Note(easy)
题目: Given an arbitrary ransom note string and another string containing letters from all the magazin ...
- 如何快速编写大项目的Makefile文件
在构建C++的后台服务时,经常需要自己来编写makefile文件,而如果没有合适的方法或模板时,编写makefile文件是一件很费时费力的事情.因此,为了帮助程序员高效准确的编写makefile文件, ...
- js 读本地文件
http://www.jb51.net/article/21191.htm <!doctype html> <html lang="en"> <hea ...
- 初步了解XMLHttpRequest对象、http请求的封装
构造器 var xhr = new XMLHttpRequest() 设置超时时间 xhr.ontimeout= 设置超时时间为 1s 设置超时时间(单位:ms) 0为永不超时 HTTP 请求的状态 ...
- 蓝桥杯T37(nim博弈)
题目链接:http://lx.lanqiao.cn/problem.page?gpid=T37 题意:中文题诶- 思路:nim博弈 个人感觉这题最难的地方是将题目转换为博弈模型,如果能将之转换为博弈模 ...
- 解决java中按照数字大小来排序文件
我们想要输出(1.jpg.2.jpg.3.jpg.10.jpg.11.jpg.20.jpg.21.jpg.31.jpg) 突然看到网上一些写法 总结:既然自己按照定义的文件名规则来处理,也可以进行使用 ...
- [Leetcode] 002. Add Two Numbers
https://leetcode.com/problems/add-two-numbers/ public class Solution { public ListNode addTwoNumbers ...
- php:判断 是否开启 SSL,CURL,ZIP,GD2,MYSQL,是否安装MEMCACHED
对于php的开发环境,通常需要去先判断下一些扩展和服务时不时已经可用~ 看过的欢迎拍砖,给意见~~ <?php /** * 判断 是否开启 SSL,CURL,ZIP,GD2,MYSQL,是否安装 ...
- D. Blocks 数学题
Panda has received an assignment of painting a line of blocks. Since Panda is such an intelligent bo ...
- SmartWeatherAPI C#版
private string GetKey(string areaId, string type, string date, string appId, string privateKey) { va ...