python实用小代码

来源:互联网 发布:传统装修公司 知乎 编辑:程序博客网 时间:2024/05/10 11:49


栈的实现

#!/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'  










原创粉丝点击