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

來源:互聯網
上載者:User

python編程中常用的12種基礎知識總結:Regex替換,遍曆目錄方法,列表按列排序、去重,字典排序,字典、列表、字串互轉,時間對象操作,命令列參數解析(getopt),print 格式化輸出,進位轉換,Python調用系統命令或者指令碼,Python 讀寫檔案。

1、Regex替換
目標: 將字串line中的 overview.gif 替換成其他字串


>>> line = '<IMG ALIGN="middle" SRC=\'#\'" /span>  >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)     >>> mo.sub(r'"\1****"',line)   '<IMG ALIGN="middle" SRC=\'#\'" /span>    >>> mo.sub(r'replace_str_\1',line)   '<IMG ALIGN="middle" replace_str_overview.gif BORDER="0" ALT="">'< /span>    >>> mo.sub(r'"testetstset"',line)   '<IMG ALIGN="middle" SRC=\'#\'" /span>  


注意: 其中 \1 是匹配到的資料,可以通過這樣的方式直接引用

2、遍曆目錄方法
在某些時候,我們需要遍曆某個目錄找出特定的檔案清單,可以通過os.walk方法來遍曆,非常方便

import os   fileList = []   rootdir = "/data"  for root, subFolders, files in os.walk(rootdir):   if '.svn' in subFolders: subFolders.remove('.svn')  # 排除特定目錄   for file in files:     if file.find(".t2t") != -1:# 尋找特定副檔名的檔案         file_dir_path = os.path.join(root,file)         fileList.append(file_dir_path)     print fileList


3、列表按列排序(list sort)
如果列表的每個元素都是一個元組(tuple),我們要根據元組的某列來排序的化,可參考如下方法

下面例子我們是根據元組的第2列和第3列資料來排序的,而且是倒序(reverse=True)


>>> 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')]   >>> print a[0][0]   2011-03-17  >>> b = sorted(a, key=lambda result: result[1],reverse=True)   >>> print b   [('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-17', '2.26', 6429600, '0.0'), ('2011-03-16', '2.26', 12036900, '-3.0')]   >>> c = sorted(a, key=lambda result: result[2],reverse=True)   >>> print c   [('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-16', '2.26', 12036900, '-3.0'), ('2011-03-17', '2.26', 6429600, '0.0')]  


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


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


5、字典排序(dict sort)
一般來說,我們都是根據字典的key來進行排序,但是我們如果想根據字典的value值來排序,就使用如下方法

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

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

6、字典,列表,字串互轉
以下是產生資料庫連接字串,從字典轉換到字串


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


下面的例子 是將字串轉化為字典


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


7、時間對象操作


將時間對象轉換成字串      >>> import datetime   >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")     '2011-01-20 14:05'    時間大小比較      >>> import time   >>> t1 = time.strptime('2011-01-20 14:05',"%Y-%m-%d %H:%M")   >>> t2 = time.strptime('2011-01-20 16:05',"%Y-%m-%d %H:%M")   >>> t1 > t2     False  >>> t1 < t2     True    時間差值計算,計算8小時前的時間      >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")     '2011-01-20 15:02'  >>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M")     '2011-01-20 07:03'    將字串轉換成時間對象      >>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d")   >>> type(endtime)     <type 'datetime.datetime'>   >>> print endtime     2010-07-01 00:00:00    將從 1970-01-01 00:00:00 UTC 到現在的秒數,格式化輸出      >>> import time   >>> a = 1302153828  >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a))     '2011-04-07 13:23:48'  


8、命令列參數解析(getopt)
通常在編寫一些日營運指令碼時,需要根據不同的條件,輸入不同的命令列選項來實現不同的功能
在Python中提供了getopt模組很好的實現了命令列參數的解析,下面距離說明。請看如下程式:


#!/usr/bin/env python   # -*- coding: utf-8 -*-   import sys,os,getopt   def usage():   print '''''  Usage: analyse_stock.py [options...]   Options:    -e : Exchange Name    -c : User-Defined Category Name   -f : Read stock info from file and save to db   -d : delete from db by stock code   -n : stock name   -s : stock code   -h : this help info   test.py -s haha -n "HA Ha"    '''    try:   opts, args = getopt.getopt(sys.argv[1:],'he:c:f:d:n:s:')   except getopt.GetoptError:   usage()   sys.exit()   if len(opts) == 0:   usage()   sys.exit()     for opt, arg in opts:    if opt in ('-h', '--help'):     usage()     sys.exit()   elif opt == '-d':     print "del stock %s" % arg   elif opt == '-f':     print "read file %s" % arg   elif opt == '-c':     print "user-defined %s " % arg   elif opt == '-e':     print "Exchange Name %s" % arg   elif opt == '-s':     print "Stock code %s" % arg   elif opt == '-n':     print "Stock name %s" % arg     sys.exit()   


9、print 格式化輸出
9.1、格式化輸出字串


截取字串輸出,下面例子將只輸出字串的前3個字母      >>> str="abcdefg"  >>> print "%.3s" % str     abc   按固定寬度輸出,不足使用空格補全,下面例子輸出寬度為10      >>> str="abcdefg"  >>> print "%10s" % str        abcdefg   截取字串,按照固定寬度輸出      >>> str="abcdefg"  >>> print "%10.3s" % str            abc   浮點類型資料位元數保留      >>> import fpformat   >>> a= 0.0030000000005  >>> b=fpformat.fix(a,6)   >>> print b     0.003000  對浮點數四捨五入,主要使用到round函數      >>> from decimal import *   >>> a ="2.26"  >>> b ="2.29"  >>> c = Decimal(a) - Decimal(b)   >>> print c     -0.03  >>> c / Decimal(a) * 100    Decimal('-1.327433628318584070796460177')   >>> Decimal(str(round(c / Decimal(a) * 100, 2)))     Decimal('-1.33')  


9.2、進位轉換
有些時候需要作不同進位轉換,可以參考下面的例子(%x 十六進位,%d 十進位,%o 十進位)

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

10、Python調用系統命令或者指令碼


使用 os.system() 調用系統命令 , 程式中無法獲得到輸出和傳回值      >>> import os   >>> os.system('ls -l /proc/cpuinfo')   >>> os.system("ls -l /proc/cpuinfo")     -r--r--r-- 1 root root 0  3月 29 16:53 /proc/cpuinfo     0    使用 os.popen() 調用系統命令, 程式中可以獲得命令輸出,但是不能得到執行的傳回值     >>> out = os.popen("ls -l /proc/cpuinfo")   >>> print out.read()     -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo     使用 commands.getstatusoutput() 調用系統命令, 程式中可以獲得命令輸出和執行的傳回值      >>> import commands   >>> commands.getstatusoutput('ls /bin/ls')     (0, '/bin/ls')  


11、Python 捕獲使用者 Ctrl+C ,Ctrl+D 事件
有些時候,需要在程式中捕獲使用者鍵盤事件,比如ctrl+c退出,這樣可以更好的安全退出程式


try:        do_some_func()   except KeyboardInterrupt:       print "User Press Ctrl+C,Exit"  except EOFError:       print "User Press Ctrl+D,Exit"  


12、Python 讀寫檔案


一次性讀入檔案到列表,速度較快,適用檔案比較小的情況下      track_file = "track_stock.conf"    fd = open(track_file)   content_list = fd.readlines()   fd.close()   for line in content_list:       print line     逐行讀入,速度較慢,適用沒有足夠記憶體讀取整個檔案(檔案太大)      fd = open(file_path)   fd.seek(0)   title = fd.readline()   keyword = fd.readline()   uuid = fd.readline()   fd.close()     寫檔案 write 與 writelines 的區別      Fd.write(str) : 把str寫到檔案中,write()並不會在str後加上一個分行符號    Fd.writelines(content) : 把content的內容全部寫到檔案中,原樣寫入,不會在每行後面加上任何東西 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.