python基础教程项目四之新闻聚合
作者:the5fire 发布时间:2021-10-03 01:31:33
标签:python,基础教程,新闻聚合
《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添加信息源和输出目的地址的。
这确实是个简单的程序,不过这个程序可是用到了分层了。
来源:https://www.the5fire.com/python-pro4-newsagent.html


猜你喜欢
- 这片文章大体概括了一些设计网页中的大问题。希望能给你做下一个网页时给予一些儿启发。1、记住:你能掌控的时间是有限的我仅仅用4秒钟就能浏览完平
- 如果有人问你,对查询执行EXPLAIN是否可以改变你的数据库,你可能会说不会; 通常都是这么认为的。EXPLAIN应该向我们展示查询是如何执
- 前言:本篇文章对如何使用golang连接并操作postgre数据库进行了简要说明。文中使用到的主要工具:DBeaver21、VSCode,G
- 前言本文参照了大佬Andrew Ng的所讲解的Tensorflow 2视频所写,本文将其中只适用于Linux的功能以及只适用于Google
- 在pycharm中设置python脚本的文件模板,让文件创建的时候就自动写上一些相关信息:1、进入pycharm的File->sett
- 快到 520 了,分享几段 520 专属 Python 代码,不多说了,下面直接上货。No.1效果:主要代码:import tur
- 引言最近在做个表情包的小程序,涉及到表情包搜索功能。我们上传表情包的时候,只有一张图,怎么搜索?这个时候我们想到就是将表情包的文字提取出来,
- >>> a = 2.5 >>> b = 2.5 >>> c = b >>&
- python中类的继承:子类继承父类,及子类拥有了父类的 属性 和 方法。python中类的初始化都是__init__()。所以父类和子类的
- 摘要1,EXEC的使用2,sp_executesql的使用MSSQL为我们提供了两种动态执行SQL语句的命令,分别是EXEC和sp_exec
- 概念节流 (throttle) 让一个函数不要执行的太频繁,减少执行过快的调用,叫节流去抖 (debounce) 去抖就是对于一定时间段的连
- 一、BeautifulSoup4 基础知识补充BeautifulSoup4 是一款 python 解析库,主要用于解析 HTML
- 一、Pytorch修改预训练模型时遇到key不匹配最近想着修改网络的预训练模型vgg.pth,但是发现当我加载预训练模型权重到新建的模型并保
- GROUP BY 语句用于结合合计函数,根据一个或多个列对结果集进行分组。1、概述“Group By”从字面意义上理解就是根据“By”指定的
- 开发一个文件上传共享网站,曾想使用下面的代码实现文件上传的功能: <form enctype="multipart/form
- 1、环境PyCharmPython 3.6pip安装的依赖包包括:requests 2.25.0、urllib3 1.26.2、docx 0
- upyter Notebook已经逐渐取代IDE成为了多平台上写简单Python脚本或应用的几家选择。Jupyter Notebook可以通
- 这个使用起来很简单,以前需要的时候在网上找的,用了感觉还不错,具体的看演示就明白了。,这个可以保留你文章中的html标记,需要你修改的就是下
- PyQt5 Qt Designer (Qt设计师)PyQt5是对Qt所有类进行封装, Qt能开发的东西, PyQt都能开发.Qt是强大的GU
- 数据库优化有很多可以讲,按照支撑的数据量来分可以分为两个阶段:单机数据库和分库分表,前者一般可以支撑500W或者10G以内的数据,超过这个值