首頁 後端開發 Python教學 python基礎教學專案四之新聞聚合

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

Apr 03, 2018 am 09:17 AM
python 新聞 專案

這篇文章主要為大家詳細介紹了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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP教程
1540
276
如何使用Python自動化從Excel到Web表單的數據輸入? 如何使用Python自動化從Excel到Web表單的數據輸入? Aug 12, 2025 am 02:39 AM

使用Python自動化將Excel數據填入網頁表單的方法是:先用pandas讀取Excel數據,再用Selenium控制瀏覽器自動填寫並提交表單;具體步驟包括安裝pandas、openpyxl和Selenium庫,下載對應瀏覽器驅動,用pandas讀取data.xlsx文件中的Name、Email、Phone等字段,通過Selenium啟動瀏覽器打開目標網頁,定位表單元素並逐行填入數據,使用WebDriverWait處理動態加載內容,添加異常處理和延遲確保穩定性,最後提交表單並循環處理所有數據行

一文了解什麼是加密貨幣交易中的情緒分析? 一文了解什麼是加密貨幣交易中的情緒分析? Aug 14, 2025 am 11:15 AM

目錄什麼是加密貨幣交易中的情緒分析?為什麼情緒分析在加密貨幣投資中很重要情緒數據的關鍵來源a.社交媒體平台b.新聞媒體c.市場指標情緒分析的工具和技術情緒分析中常用的工具:採用的技術:將情感分析整合到交易策略中交易者如何使用它:策略示例:假設BTC交易場景場景設置:情感信號:交易者的解讀:決策:結果:情感分析的局限性和風險利用情感進行更智能的加密貨幣交易理解市場情緒在加密貨幣交易中變得越來越重要。最近一項2025年的研究由Hamid

如何處理不適合內存的Python中的大型數據集? 如何處理不適合內存的Python中的大型數據集? Aug 14, 2025 pm 01:00 PM

當Python中處理超出內存的大型數據集時,不能一次性加載到RAM中,而應採用分塊處理、磁盤存儲或流式處理等策略;可通過Pandas的chunksize參數分塊讀取CSV文件並逐塊處理,使用Dask實現類似Pandas語法的並行化和任務調度以支持大內存數據操作,編寫生成器函數逐行讀取文本文件減少內存佔用,利用Parquet列式存儲格式結合PyArrow高效讀取特定列或行組,使用NumPy的memmap對大型數值數組進行內存映射以按需訪問數據片段,或將數據存入SQLite或DuckDB等輕量級數據

如何調試您的Python代碼 如何調試您的Python代碼 Aug 13, 2025 am 12:18 AM

useprint()statement stocheckVaruesAndExeCutionFlow,添加labelsandtypesforclarity,andremovethembeforeCommitting; 2.usethephepythondebugger(pdb)withBreakpoint(pock)

如何在Sublime文本中調試Python代碼? 如何在Sublime文本中調試Python代碼? Aug 14, 2025 pm 04:51 PM

UseSublimeText’sbuildsystemtorunPythonscriptsandcatcherrorsbypressingCtrl Baftersettingthecorrectbuildsystemorcreatingacustomone.2.Insertstrategicprint()statementstocheckvariablevalues,types,andexecutionflow,usinglabelsandrepr()forclarity.3.Installth

如何在Sublime文本中運行Python代碼? 如何在Sublime文本中運行Python代碼? Aug 16, 2025 am 04:58 AM

確保已安裝Python並將其添加到系統PATH,通過終端運行python--version或python3--version驗證;2.將Python文件保存為.py擴展名,如hello.py;3.在SublimeText中創建自定義構建系統,Windows用戶使用{"cmd":["python","-u","$file"]},macOS/Linux用戶使用{"cmd":["python3

如何在VScode中調試Python腳本 如何在VScode中調試Python腳本 Aug 16, 2025 am 02:53 AM

要調試Python腳本,需先安裝Python擴展並配置解釋器,然後創建launch.json文件設置調試配置,接著在代碼中設置斷點並按F5啟動調試,腳本將在斷點處暫停,允許檢查變量和單步執行,最終通過查看控制台輸出、添加日誌或調整參數等方式排查問題,確保環境正確後調試過程簡單高效。

如何使嵌套列表或python中的列表列表更平坦 如何使嵌套列表或python中的列表列表更平坦 Aug 12, 2025 am 09:49 AM

FlatteninganestedlistinPythonconvertsalistwithsublistsintoasingleflatlist,andthebestmethoddependsonthenestingdepthanddatasize.Forone-levelnesting,uselistcomprehensionlike[itemforsublistinnested_listforiteminsublist]oritertools.chain.from_iterable(nes

See all articles