python編程中經常使用的12種基礎知識總結

python編程中經常使用的12種基礎知識總結:正則表達式替換,遍歷目錄方法,列表按列排序、去重,字典排序,字典、列表、字符串互轉,時間對象操 做,命令行參數解析(getopt),print 格式化輸出,進制轉換,Python調用系統命令或者腳本,Python 讀寫文件。

一、正則表達式替換
目標: 將字符串line中的 overview.gif 替換成其餘字符串 python

 
  1. >>> line = '<IMG ALIGN="middle" SRC=\'#\'" /span> 
  2. >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)  
  3.  
  4. >>> mo.sub(r'"\1****"',line)  
  5. '<IMG ALIGN="middle" SRC=\'#\'" /span> 
  6.  
  7. >>> mo.sub(r'replace_str_\1',line)  
  8. '<IMG ALIGN="middle" replace_str_overview.gif BORDER="0" ALT="">'< /span> 
  9.  
  10. >>> mo.sub(r'"testetstset"',line)  
  11. '<IMG ALIGN="middle" SRC=\'#\'" /span> 

注意: 其中 \1 是匹配到的數據,能夠經過這樣的方式直接引用 正則表達式

二、遍歷目錄方法
在某些時候,咱們須要遍歷某個目錄找出特定的文件列表,能夠經過os.walk方法來遍歷,很是方便 數據庫

 
  1. import os  
  2. fileList = []  
  3. rootdir = "/data" 
  4. for root, subFolders, files in os.walk(rootdir):  
  5. if '.svn' in subFolders: subFolders.remove('.svn')  # 排除特定目錄  
  6. for file in files:  
  7.   if file.find(".t2t") != -1:# 查找特定擴展名的文件  
  8.       file_dir_path = os.path.join(root,file)  
  9.       fileList.append(file_dir_path)  
  10.  
  11. print fileList 

三、列表按列排序(list sort)
若是列表的每一個元素都是一個元組(tuple),咱們要根據元組的某列來排序的化,可參考以下方法 編程

下面例子咱們是根據元組的第2列和第3列數據來排序的,並且是倒序(reverse=True) 安全

 
  1. >>> a = [('2011-03-17''2.26'6429600'0.0'), ('2011-03-16''2.26'12036900'-3.0'), ('2011-03-15''2.33'15615500,'-19.1')]  
  2. >>> print a[0][0]  
  3. 2011-03-17 
  4. >>> b = sorted(a, key=lambda result: result[1],reverse=True)  
  5. >>> print b  
  6. [('2011-03-15''2.33'15615500'-19.1'), ('2011-03-17''2.26'6429600'0.0'), ('2011-03-16''2.26'12036900'-3.0')]  
  7. >>> c = sorted(a, key=lambda result: result[2],reverse=True)  
  8. >>> print c  
  9. [('2011-03-15''2.33'15615500'-19.1'), ('2011-03-16''2.26'12036900'-3.0'), ('2011-03-17''2.26'6429600'0.0')] 

四、列表去重(list uniq)
有時候須要將list中重複的元素刪除,就要使用以下方法 app

 
  1. >>> lst= [(1,'sss'),(2,'fsdf'),(1,'sss'),(3,'fd')]  
  2. >>> set(lst)  
  3. set([(2'fsdf'), (3'fd'), (1'sss')])  
  4. >>>  
  5. >>> lst = [113445676]  
  6. >>> set(lst)  
  7. set([134567]) 

五、字典排序(dict sort)
通常來講,咱們都是根據字典的key來進行排序,可是咱們若是想根據字典的value值來排序,就使用以下方法 運維

 
  1. >>> from operator import itemgetter  
  2. >>> aa = {"a":"1","sss":"2","ffdf":'5',"ffff2":'3'}  
  3. >>> sort_aa = sorted(aa.items(),key=itemgetter(1))  
  4. >>> sort_aa  
  5. [('a''1'), ('sss''2'), ('ffff2''3'), ('ffdf''5')] 

從上面的運行結果看到,按照字典的value值進行排序的 svn

六、字典,列表,字符串互轉
如下是生成數據庫鏈接字符串,從字典轉換到字符串 函數

 
  1. >>> params = {"server":"mpilgrim""database":"master""uid":"sa""pwd":"secret"}  
  2. >>> ["%s=%s" % (k, v) for k, v in params.items()]  
  3. ['server=mpilgrim''uid=sa''database=master''pwd=secret']  
  4. >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])  
  5. 'server=mpilgrim;uid=sa;database=master;pwd=secret' 

下面的例子 是將字符串轉化爲字典 ui

 
  1. >>> a = 'server=mpilgrim;uid=sa;database=master;pwd=secret' 
  2. >>> aa = {}  
  3. >>> for i in a.split(';'):aa[i.split('=',1)[0]] = i.split('=',1)[1]  
  4. ...   
  5. >>> aa  
  6. {'pwd''secret''database''master''uid''sa''server''mpilgrim'

七、時間對象操做

 
  1. 將時間對象轉換成字符串     
  2. >>> import datetime  
  3. >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")  
  4.   '2011-01-20 14:05' 
  5.  
  6. 時間大小比較     
  7. >>> import time  
  8. >>> t1 = time.strptime('2011-01-20 14:05',"%Y-%m-%d %H:%M")  
  9. >>> t2 = time.strptime('2011-01-20 16:05',"%Y-%m-%d %H:%M")  
  10. >>> t1 > t2  
  11.   False 
  12. >>> t1 < t2  
  13.   True 
  14.  
  15. 時間差值計算,計算8小時前的時間     
  16. >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")  
  17.   '2011-01-20 15:02' 
  18. >>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M")  
  19.   '2011-01-20 07:03' 
  20.  
  21. 將字符串轉換成時間對象     
  22. >>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d")  
  23. >>> type(endtime)  
  24.   <type 'datetime.datetime'>  
  25. >>> print endtime  
  26.   2010-07-01 00:00:00 
  27.  
  28. 將從 1970-01-01 00:00:00 UTC 到如今的秒數,格式化輸出   
  29.  
  30. >>> import time  
  31. >>> a = 1302153828 
  32. >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a))  
  33.   '2011-04-07 13:23:48' 

八、命令行參數解析(getopt)
一般在編寫一些日運維腳本時,須要根據不一樣的條件,輸入不一樣的命令行選項來實現不一樣的功能
在Python中提供了getopt模塊很好的實現了命令行參數的解析,下面距離說明。請看以下程序:

 
  1. #!/usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3. import sys,os,getopt  
  4. def usage():  
  5. print '''''  
  6. Usage: analyse_stock.py [options...]  
  7. Options:   
  8. -e : Exchange Name   
  9. -c : User-Defined Category Name  
  10. -f : Read stock info from file and save to db  
  11. -d : delete from db by stock code  
  12. -n : stock name  
  13. -s : stock code  
  14. -h : this help info  
  15. test.py -s haha -n "HA Ha"   
  16. ''' 
  17.  
  18. try:  
  19. opts, args = getopt.getopt(sys.argv[1:],'he:c:f:d:n:s:')  
  20. except getopt.GetoptError:  
  21. usage()  
  22. sys.exit()  
  23. if len(opts) == 0:  
  24. usage()  
  25. sys.exit()  
  26.  
  27. for opt, arg in opts:   
  28. if opt in ('-h''--help'):  
  29.   usage()  
  30.   sys.exit()  
  31. elif opt == '-d':  
  32.   print "del stock %s" % arg  
  33. elif opt == '-f':  
  34.   print "read file %s" % arg  
  35. elif opt == '-c':  
  36.   print "user-defined %s " % arg  
  37. elif opt == '-e':  
  38.   print "Exchange Name %s" % arg  
  39. elif opt == '-s':  
  40.   print "Stock code %s" % arg  
  41. elif opt == '-n':  
  42.   print "Stock name %s" % arg  
  43.  
  44. sys.exit()  

九、print 格式化輸出
9.一、格式化輸出字符串

 
  1. 截取字符串輸出,下面例子將只輸出字符串的前3個字母     
  2. >>> str="abcdefg" 
  3. >>> print "%.3s" % str  
  4.   abc  
  5. 按固定寬度輸出,不足使用空格補全,下面例子輸出寬度爲10     
  6. >>> str="abcdefg" 
  7. >>> print "%10s" % str  
  8.      abcdefg  
  9. 截取字符串,按照固定寬度輸出     
  10. >>> str="abcdefg" 
  11. >>> print "%10.3s" % str  
  12.          abc  
  13. 浮點類型數據位數保留     
  14. >>> import fpformat  
  15. >>> a= 0.0030000000005 
  16. >>> b=fpformat.fix(a,6)  
  17. >>> print b  
  18.   0.003000 
  19. 對浮點數四捨五入,主要使用到round函數     
  20. >>> from decimal import *  
  21. >>> a ="2.26" 
  22. >>> b ="2.29" 
  23. >>> c = Decimal(a) - Decimal(b)  
  24. >>> print c  
  25.   -0.03 
  26. >>> c / Decimal(a) * 100 
  27.   Decimal('-1.327433628318584070796460177')  
  28. >>> Decimal(str(round(c / Decimal(a) * 1002)))  
  29.   Decimal('-1.33'

9.二、進制轉換
有些時候須要做不一樣進制轉換,能夠參考下面的例子(%x 十六進制,%d 十進制,%o 十進制)

 
  1. >>> num = 10 
  2. >>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num)  
  3.   Hex = a,Dec = 10,Oct = 12 

十、Python調用系統命令或者腳本

 
  1. 使用 os.system() 調用系統命令 , 程序中沒法得到到輸出和返回值     
  2. >>> import os  
  3. >>> os.system('ls -l /proc/cpuinfo')  
  4. >>> os.system("ls -l /proc/cpuinfo")  
  5.   -r--r--r-- 1 root root 0  3月 29 16:53 /proc/cpuinfo  
  6.   0 
  7.  
  8. 使用 os.popen() 調用系統命令, 程序中能夠得到命令輸出,可是不能獲得執行的返回值    
  9. >>> out = os.popen("ls -l /proc/cpuinfo")  
  10. >>> print out.read()  
  11.   -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo  
  12.  
  13. 使用 commands.getstatusoutput() 調用系統命令, 程序中能夠得到命令輸出和執行的返回值     
  14. >>> import commands  
  15. >>> commands.getstatusoutput('ls /bin/ls')  
  16.   (0'/bin/ls'

十一、Python 捕獲用戶 Ctrl+C ,Ctrl+D 事件
有些時候,須要在程序中捕獲用戶鍵盤事件,好比ctrl+c退出,這樣能夠更好的安全退出程序

 
  1. try:   
  2.     do_some_func()  
  3. except KeyboardInterrupt:  
  4.     print "User Press Ctrl+C,Exit" 
  5. except EOFError:  
  6.     print "User Press Ctrl+D,Exit" 

十二、Python 讀寫文件

 
  1. 一次性讀入文件到列表,速度較快,適用文件比較小的狀況下     
  2. track_file = "track_stock.conf"   
  3. fd = open(track_file)  
  4. content_list = fd.readlines()  
  5. fd.close()  
  6. for line in content_list:  
  7.     print line  
  8.  
  9. 逐行讀入,速度較慢,適用沒有足夠內存讀取整個文件(文件太大)     
  10. fd = open(file_path)  
  11. fd.seek(0)  
  12. title = fd.readline()  
  13. keyword = fd.readline()  
  14. uuid = fd.readline()  
  15. fd.close()  
  16.  
  17. 寫文件 write 與 writelines 的區別   
  18.  
  19. Fd.write(str) : 把str寫到文件中,write()並不會在str後加上一個換行符   
  20. Fd.writelines(content) : 把content的內容所有寫到文件中,原樣寫入,不會在每行後面加上任何東西 
相關文章
相關標籤/搜索