Python程式設計中常用的12種基礎知識總結
Python程式設計中常用的12種基礎知識總結:正規表示式替換,遍歷目錄方法,列表按列排序、去重,字典排序,字典、列表、字串互轉,時間物件操作,命令列引數解析(getopt),print 格式化輸出,進位制轉換,Python呼叫系統命令或者指令碼,Python 讀寫檔案。
1、正規表示式替換
目標: 將字串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的內容全部寫到檔案中,原樣寫入,不會在每行後面加上任何東西
相關文章
- Python 程式設計中常用的 12 種基礎知識總結Python程式設計
- Python 程式設計中常用的12種基礎知識總結Python程式設計
- 程式設計基礎知識程式設計
- python基礎語法知識點總結Python
- 好程式設計師Java培訓分享Java基礎知識總結程式設計師Java
- MySQL基礎知識和常用命令總結MySql
- 《java程式設計基礎》java的基礎知識(三)Java程式設計
- Java基礎知識總結Java
- React 基礎知識總結React
- SpringIOC基礎知識總結Spring
- Rust 基礎知識總結Rust
- 索引基礎知識總結索引
- 【python----發軔之始】【基礎知識總結】Python
- 網路程式設計基礎知識程式設計
- Python程式設計基礎Task12Python程式設計
- Java多執行緒程式設計基礎知識彙總Java執行緒程式設計
- Python基礎知識之常用框架Flask!Python框架Flask
- Java基礎知識點總結Java
- JS基礎知識深入總結JS
- TCP/IP 基礎知識總結TCP
- JS基礎知識總結(1)JS
- CSS基礎知識總結(4)CSS
- JS基礎知識總結(2)JS
- ES 基礎知識點總結
- Java基礎知識總結-1Java
- Redis 基礎知識點總結Redis
- 好程式設計師Python培訓分享Python入門基礎知識程式設計師Python
- [鞏固基礎]總結Python基礎知識的14張思維導圖Python
- python,函式各種基礎知識Python函式
- yii2 基礎知識總結
- 前端知識點總結——JavaScript基礎前端JavaScript
- 演算法基礎知識總結演算法
- Flutter 知識點總結-基礎篇Flutter
- Java基礎對反射知識總結Java反射
- Java併發程式設計——基礎知識(二)Java程式設計
- Java併發程式設計——基礎知識(一)Java程式設計
- Python網路程式設計(基礎總結入門經典)Python程式設計
- 後端程式設計師必備的 Linux 基礎知識+常見命令(近萬字總結)後端程式設計師Linux
- 軟體設計師:程式設計語言基礎知識程式設計