python基礎教學專案四之新聞聚合

不言
發布: 2018-04-03 09:17:34
原創
1648 人瀏覽過

這篇文章主要為大家詳細介紹了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&#39;s News</title>
        </head>
        <body>
        <h1>Today&#39;s News</hi>
        &#39;&#39;&#39;
        print >> out, &#39;<ul>&#39;
        id = 0
        for item in items:
            id += 1
            print >> out, &#39;<li><a href="#" rel="external nofollow" >%s</a></li>&#39; % (id,item.title)
        print >> out, &#39;</ul>&#39;
        id = 0
        for item in items:
            id += 1
            print >> out, &#39;<h2><a name="%i">%s</a></h2>&#39; % (id,item.title)
            print >> out, &#39;<pre class="brush:php;toolbar:false">%s
' % item.body print >> out, ''' ''' def runDefaultSetup(): agent = NewsAgent() bbc_url = 'http://news.bbc.co.uk/text_only.stm' bbc_title = r'(?s)a href="[^" rel="external nofollow" ]*">\s*\s*(.*?)\s*' bbc_body = r'(?s)\s*
\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基礎教學專案四之新聞聚合的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!