+ -
当前位置:首页 → 问答吧 → Python 常用代码片段

Python 常用代码片段

时间:2011-03-23

来源:互联网

  1. 1.生成随机数
  2.           import random    #这个是注释,引入模块
  3.           rnd = random.randint(1,500)#生成1-500之间的随机数

  4. 2.读文件

  5.          f = open("c:\\1.txt","r")
  6.          lines = f.readlines()#读取全部内容
  7.          for line in lines
  8.                  print line
  9. 3.写文件
  10.         f = open("c:\\1.txt","r+")#可读可写模式
  11.         f.write("123")#写入字符串

  12. 4.正则表达式,读取tomcat的日志并打印日期

  13.      import re
  14.      regx = "\d\d\d\d-\d\d-\d+"
  15.      f = open("c:\stdout.log","r")
  16.      i = 0
  17.      for str in f.readlines():
  18.         if re.search(regx,str):
  19.              Response.write(str+"<br>")
  20.               if i>10:break#由于是测试,只分析十行
  21.               i=i+1
  22.      f.close();

  23. 5.连接数据库

  24. import pgdb

  25. conn = pgdb.connect

  26. (host='localhost',databse='qingfeng',user='qingfeng',password='123')

  27.         cur = conn.cursor()

  28.         cur.execute("select * from dream")

  29.         print cur.rowcount

  30. 6.SAX处理xml:

  31.       import string
  32.       from xml.sax import saxlib, saxexts

  33.       class QuotationHandler(saxlib.HandlerBase):
  34.           """Crude sax extractor for quotations.dtd document"""

  35.           def __init__(self):
  36.                   self.in_quote = 0
  37.                   self.thisquote = ''

  38.           def startDocument(self):
  39.               print '--- Begin Document ---'

  40.           def startElement(self, name, attrs):
  41.               if name == 'quotation':
  42.                   print 'QUOTATION:'
  43.                   self.in_quote = 1
  44.               else:
  45.                   self.thisquote = self.thisquote + '{'

  46.           def endElement(self, name):
  47.               if name == 'quotation':
  48.                   print string.join(string.split(self.thisquote[:230]))+'...',
  49.                   print '('+str(len(self.thisquote))+' bytes)\n'
  50.                   self.thisquote = ''
  51.                   self.in_quote = 0
  52.               else:
  53.                   self.thisquote = self.thisquote + '}'

  54.           def characters(self, ch, start, length):
  55.               if self.in_quote:
  56.                   self.thisquote = self.thisquote + ch[start:start+length]

  57.       if __name__ == '__main__':
  58.           parser  = saxexts.XMLParserFactory.make_parser()
  59.           handler = QuotationHandler()
  60.           parser.setDocumentHandler(handler)
  61.           parser.parseFile(open("sample.xml"))
  62.           parser.close()


  63. 7.python的GUI模块标准的是Tkinter,也有QT和MFC的模块,有兴趣的大家自己搜索下

  64.         import Tkinter

  65.         root=Tkinter.Tk()

  66.         my=Label(root,"Welcome to python's world")

  67.         my.pack()

  68.         root.mainloop()
复制代码

作者: life-boy   发布时间: 2011-03-23

不错,支持下

作者: freetstar   发布时间: 2011-03-23