python實用小代碼

來源:互聯網
上載者:User
文章目錄
  • 棧的實現
  • Python抓取oschina的最新部落格列表
  •  python寫的一個郵件發生器

棧的實現

#!/usr/bin/env python #coding=utf-8 #python version 2.7.4class stack:    def __init__(self,list=None):        self.contain = list         self.msize=100;        self.top = 0;    def getTop(self):        if(self.top>0):            return self.contain[self.top-1]        else:            return None    def getLength(self):        return len(contain);    def push(self,str):        if(self.top==self.msize):            return -1        self.contain.append(str)        self.top=self.top +1    def pop(self):        try:            res=self.contain.pop()            return res;        except IndexError:            return None        li = [1,'51','15']st = stack(li)va='5'print st.pop()print st.pop()st.push('fdef')print st.pop()print st.pop()
Python抓取oschina的最新部落格列表這個功能在oschina上有人寫,但是個人感覺不怎麼樣,所以修改了一下,用棧進行匹配,即快也方便了很多,代碼比較易理解

#!/usr/bin/env python #coding=utf-8 #python version:2.7.4#system:windows xpimport sysimport httplib2import HTMLParserdef getPageContent(url):    '''    使用httplib2用編程的方式根據url擷取網頁內容    將bytes形式的內容轉換成utf-8的字串    '''    #使用ie9的user-agent,如果不設定user-agent將會得到403禁止訪問    headers={'user-agent':'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)',            'cache-control':'no-cache'}    if url:         response,content = httplib2.Http().request(url,headers=headers)                  if response.status == 200 :            return contentclass stack:    def __init__(self,size=100,list=None):        self.contain=[]        self.msize=size;        self.top = 0;    def getTop(self):        if(self.top>0):            return self.contain[self.top-1]        else:            return None    def getLength(self):        return len(self.contain);    def push(self,data):        if(self.top==self.msize):            return -1        self.contain.append(data)        self.top=self.top +1    def pop(self):        try:            res=self.contain.pop()            if(self.top>0):                self.top=self.top-1            return res;        except IndexError:            return None        class ParserOschinaNew(HTMLParser.HTMLParser):    def __init__(self):        HTMLParser.HTMLParser.__init__(self)        self.st=stack(size=1000)        self.st.push('over')            def handle_starttag(self,tag,attrs):        stack_size = self.st.getLength()        if stack_size==1 and tag=='ul':            for name,value in attrs:                if (name=='class' and value=='BlogList'):                    self.st.push('ul')                    break;        if (stack_size==2 and tag=='li' ):            self.st.push('li')        if (stack_size==3 and tag=='h3' ):            self.st.push('h3')            text = '部落格標題:'.decode('utf-8').encode('gb2312','ignore')            print '%s'%text        if (stack_size==3 and tag=='p' ):            self.st.push('p')            text = '本文部分:'.decode('utf-8').encode('gb2312','ignore')            print '%s'%text        if (stack_size==3 and tag=='div' ):            for name,value in attrs:                if (name=='class' and value=='date'):                    self.st.push('div')                    text = '作者:'.decode('utf-8').encode('gb2312','ignore')                    print '%s'%text                                    def handle_data(self ,data):        stack_size = self.st.getLength()        if (stack_size==4):            print data.decode('utf-8').encode('gb2312','ignore')      def handle_endtag(self,tag):        stack_size = self.st.getLength()        stack_tag = self.st.getTop()        if ('h3'==tag and 'h3'==stack_tag):            self.st.pop()        if ('p'==tag and 'p'==stack_tag):            self.st.pop()        if ('div'==tag and 'div'==stack_tag):            self.st.pop()                if ('li'==tag and 'li'==stack_tag):            self.st.pop()        if ('ul'==tag and 'ul'==stack_tag):            self.st.pop()            if('over'==self.st.getTop()):                          print "this is end!"        if __name__ == '__main__':    pageC = getPageContent('http://www.oschina.net/blog/more?p=1') #   pageC = pageC.decode('utf-8').encode('gb2312','ignore')       my = ParserOschinaNew()    my.feed(pageC)

 python寫的一個郵件發生器

作者:AshlingR  郵箱:AshlingR@163.com  時間:2013.6.2    #!/usr/bin/env python  # -*- coding: utf-8 -*-  #匯入smtplib和MIMEText  import smtplib  from email.mime.text import MIMEText    #配置資訊  mail_to             ='XXXXX@163.com'  mail_server         ='smtp.qq.com'#163:smtp.163.com  qq:smtp.qq.com  mail_user_name      ='123456879'  mail_user_passwd    ='123456'  mail_postfix        ='qq.com'    info_list = [ mail_server, mail_user_name,mail_user_passwd ,mail_postfix]    ''''' to_list:    目的郵件地址 sub:        郵件的主題 content:    郵件的內容 '''  def send_mail(list,to_list,sub,content):      #設定伺服器,使用者名稱、口令以及郵箱的尾碼    #    assert type(to_list) == list      mail_server=str(list[0])# 'smtp.stu.edu.cn'      mail_user_name=str(list[1])#'11lrao'      mail_user_passwd=str(list[2])## 'raoliang'      mail_postfix=str(list[3])#'stu.edu.cn'            print type(mail_server),mail_server             scr_addr='send machine'+'<'+mail_user_name+'@'+mail_postfix+'>'      msg = MIMEText(content,_subtype='text/plain',_charset='gb2312')      msg['Subject'] = sub      msg['From'] = scr_addr ;      msg['To'] = to_list      try:          s = smtplib.SMTP()          s.connect(mail_server)          s.login(mail_user_name,mail_user_passwd)          s.sendmail(scr_addr, to_list, msg.as_string())          s.close()          print '1'          return True      except Exception, e:          print 'mail error:'          print str(e)          return False  if __name__ == '__main__':      if send_mail(info_list,mail_to,'titile0','content0'):          print 'send success'      else:          print 'send failed'  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.