Python 常用代码片段

简介:

[python] view plaincopy

  1. 1.生成随机数  

  2.           import random    #这个是注释,引入模块  

  3.           rnd = random.randint(1,500)#生成1-500之间的随机数  

  4.   

  5. 2.读文件  

  6.   

  7.          f = open("c:\\1.txt","r")  

  8.          lines = f.readlines()#读取全部内容  

  9.          for line in lines  

  10.                  print line  

  11. 3.写文件  

  12.         f = open("c:\\1.txt","r+")#可读可写模式  

  13.         f.write("123")#写入字符串  

  14.   

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

  16.   

  17.      import re  

  18.      regx = "\d\d\d\d-\d\d-\d+"  

  19.      f = open("c:\stdout.log","r")  

  20.      i = 0  

  21.      for str in f.readlines():  

  22.         if re.search(regx,str):  

  23.              Response.write(str+"
    "
    )  

  24.               if i>10:break#由于是测试,只分析十行  

  25.               i=i+1  

  26.      f.close();  

  27.   

  28. 5.连接数据库  

  29.   

  30. import pgdb  

  31.   

  32. conn = pgdb.connect  

  33.   

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

  35.   

  36.         cur = conn.cursor()   

  37.   

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

  39.   

  40.         print cur.rowcount  

  41.   

  42. 6.SAX处理xml:  

  43.   

  44.       import string  

  45.       from xml.sax import saxlib, saxexts  

  46.   

  47.       class QuotationHandler(saxlib.HandlerBase):  

  48.           """Crude sax extractor for quotations.dtd document"""  

  49.   

  50.           def __init__(self):  

  51.                   self.in_quote = 0  

  52.                   self.thisquote = ''  

  53.   

  54.           def startDocument(self):  

  55.               print '--- Begin Document ---'  

  56.   

  57.           def startElement(self, name, attrs):  

  58.               if name == 'quotation':  

  59.                   print 'QUOTATION:'  

  60.                   self.in_quote = 1  

  61.               else:  

  62.                   self.thisquote = self.thisquote + '{'  

  63.   

  64.           def endElement(self, name):  

  65.               if name == 'quotation':  

  66.                   print string.join(string.split(self.thisquote[:230]))+'...',  

  67.                   print '('+str(len(self.thisquote))+' bytes)\n'  

  68.                   self.thisquote = ''  

  69.                   self.in_quote = 0  

  70.               else:  

  71.                   self.thisquote = self.thisquote + '}'  

  72.   

  73.           def characters(self, ch, start, length):  

  74.               if self.in_quote:  

  75.                   self.thisquote = self.thisquote + ch[start:start+length]  

  76.   

  77.       if __name__ == '__main__':  

  78.           parser  = saxexts.XMLParserFactory.make_parser()  

  79.           handler = QuotationHandler()  

  80.           parser.setDocumentHandler(handler)  

  81.           parser.parseFile(open("sample.xml"))  

  82.           parser.close()  

  83.   

  84.   

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

  86.   

  87.         import Tkinter  

  88.   

  89.         root=Tkinter.Tk()  

  90.   

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

  92.   

  93.         my.pack()  

  94.   

  95.         root.mainloop()  










本文转自 chengxuyonghu 51CTO博客,原文链接:http://blog.51cto.com/6226001001/1638071,如需转载请自行联系原作者
目录
相关文章
|
5月前
|
存储 算法 调度
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
【复现】【遗传算法】考虑储能和可再生能源消纳责任制的售电公司购售电策略(Python代码实现)
275 26
|
5月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
478 1
|
5月前
|
机器学习/深度学习 算法 调度
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
基于多动作深度强化学习的柔性车间调度研究(Python代码实现)
294 1
|
4月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
311 100
|
4月前
|
开发者 Python
Python列表推导式:一行代码的艺术与力量
Python列表推导式:一行代码的艺术与力量
483 95
|
5月前
|
Python
Python的简洁之道:5个让代码更优雅的技巧
Python的简洁之道:5个让代码更优雅的技巧
298 104
|
5月前
|
开发者 Python
Python神技:用列表推导式让你的代码更优雅
Python神技:用列表推导式让你的代码更优雅
550 99
|
4月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
214 88
|
5月前
|
IDE 开发工具 开发者
Python类型注解:提升代码可读性与健壮性
Python类型注解:提升代码可读性与健壮性
313 102
|
4月前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。
884 68

推荐镜像

更多