日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
Python語(yǔ)言的12個(gè)基礎(chǔ)知識(shí)點(diǎn)小結(jié)

 python編程中常用的12種基礎(chǔ)知識(shí)總結(jié):正則表達(dá)式替換,遍歷目錄方法,列表按列排序、去重、字典排序、字典、列表、字符串互轉(zhuǎn),時(shí)間對(duì)象操作,命令行參數(shù)解析(getopt),print 格式化輸出,進(jìn)制轉(zhuǎn)換,Python調(diào)用系統(tǒng)命令或者腳本,Python 讀寫文件。

為麻山等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及麻山網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為網(wǎng)站建設(shè)、成都做網(wǎng)站、麻山網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!

1、正則表達(dá)式替換

目標(biāo): 將字符串line中的 overview.gif 替換成其他字符串。

 
 
 
  1. >>> line = '
  2. >>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)  
  3. >>> mo.sub(r'"\1****"',line) 
  4. ' 
  5. >>> mo.sub(r'replace_str_\1',line) 
  6. ''< /span> 
  7. >>> mo.sub(r'"testetstset"',line) 
  8. ' 

 注意: 其中 \1 是匹配到的數(shù)據(jù),可以通過這樣的方式直接引用。

2、遍歷目錄方法

在某些時(shí)候,我們需要遍歷某個(gè)目錄找出特定的文件列表,可以通過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:# 查找特定擴(kuò)展名的文件 
  8.       file_dir_path = os.path.join(root,file) 
  9.       fileList.append(file_dir_path)  
  10. print fileList 

 3、列表按列排序(list sort)

如果列表的每個(gè)元素都是一個(gè)元組(tuple),我們要根據(jù)元組的某列來排序的化,可參考如下方法:

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

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

 4、列表去重(list uniq)

有時(shí)候需要將list中重復(fù)的元素刪除,就要使用如下方法:

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

 5、字典排序(dict sort)

一般來說,我們都是根據(jù)字典的key來進(jìn)行排序,但是我們?nèi)绻敫鶕?jù)字典的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')] 

 6、字典,列表,字符串互轉(zhuǎn)

以下是生成數(shù)據(jù)庫(kù)連接字符串,從字典轉(zhuǎn)換到字符串。

 
 
 
  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' 

 下面的例子,是將字符串轉(zhuǎn)化為字典。

 
 
 
  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'} 

 7、時(shí)間對(duì)象操作

將時(shí)間對(duì)象轉(zhuǎn)換成字符串。

 
 
 
  1. >>> import datetime 
  2. >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M") 
  3.   '2011-01-20 14:05'  

 時(shí)間大小比較。

 
 
 
  1. >>> import time 
  2. >>> t1 = time.strptime('2011-01-20 14:05',"%Y-%m-%d %H:%M") 
  3. >>> t2 = time.strptime('2011-01-20 16:05',"%Y-%m-%d %H:%M") 
  4. >>> t1 > t2 
  5.   False 
  6. >>> t1 < t2 
  7.   True  

 時(shí)間差值計(jì)算,計(jì)算8小時(shí)前的時(shí)間。

 
 
 
  1. >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M") 
  2.   '2011-01-20 15:02' 
  3. >>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M") 
  4.   '2011-01-20 07:03'  

 將字符串轉(zhuǎn)換成時(shí)間對(duì)象。

 
 
 
  1. >>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d") 
  2. >>> type(endtime) 
  3.    
  4. >>> print endtime 
  5.   2010-07-01 00:00:00  

 將從 1970-01-01 00:00:00 UTC 到現(xiàn)在的秒數(shù),格式化輸出。

 
 
 
  1. >>> import time 
  2. >>> a = 1302153828 
  3. >>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a)) 
  4.   '2011-04-07 13:23:48' 

 8、命令行參數(shù)解析(getopt)

通常在編寫一些日運(yùn)維腳本時(shí),需要根據(jù)不同的條件,輸入不同的命令行選項(xiàng)來實(shí)現(xiàn)不同的功能。

在Python中提供了getopt模塊很好的實(shí)現(xiàn)了命令行參數(shù)的解析,下面距離說明。請(qǐng)看如下程序:

 
 
 
  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. try: 
  18. opts, args = getopt.getopt(sys.argv[1:],'he:c:f:d:n:s:') 
  19. except getopt.GetoptError: 
  20. usage() 
  21. sys.exit() 
  22. if len(opts) == 0: 
  23. usage() 
  24. sys.exit()  
  25. for opt, arg in opts: 
  26. if opt in ('-h', '--help'): 
  27.   usage() 
  28.   sys.exit() 
  29. elif opt == '-d': 
  30.   print "del stock %s" % arg 
  31. elif opt == '-f': 
  32.   print "read file %s" % arg 
  33. elif opt == '-c': 
  34.   print "user-defined %s " % arg 
  35. elif opt == '-e': 
  36.   print "Exchange Name %s" % arg 
  37. elif opt == '-s': 
  38.   print "Stock code %s" % arg 
  39. elif opt == '-n': 
  40.   print "Stock name %s" % arg  
  41. sys.exit() 

 9、print 格式化輸出

9.1、格式化輸出字符串

截取字符串輸出,下面例子將只輸出字符串的前3個(gè)字母。

 
 
 
  1. >>> str="abcdefg" 
  2. >>> print "%.3s" % str 
  3.   abc 

 按固定寬度輸出,不足使用空格補(bǔ)全,下面例子輸出寬度為10。

 
 
 
  1. >>> str="abcdefg" 
  2. >>> print "%10s" % str 
  3.      abcdefg 

 截取字符串,按照固定寬度輸出。

 
 
 
  1. >>> str="abcdefg" 
  2. >>> print "%10.3s" % str 
  3.          abc 

 浮點(diǎn)類型數(shù)據(jù)位數(shù)保留。

 
 
 
  1. >>> import fpformat 
  2. >>> a= 0.0030000000005 
  3. >>> b=fpformat.fix(a,6) 
  4. >>> print b 
  5.   0.003000 

 對(duì)浮點(diǎn)數(shù)四舍五入,主要使用到round函數(shù)。

 
 
 
  1. >>> from decimal import * 
  2. >>> a ="2.26" 
  3. >>> b ="2.29" 
  4. >>> c = Decimal(a) - Decimal(b) 
  5. >>> print c 
  6.   -0.03 
  7. >>> c / Decimal(a) * 100 
  8.   Decimal('-1.327433628318584070796460177') 
  9. >>> Decimal(str(round(c / Decimal(a) * 100, 2))) 
  10.   Decimal('-1.33') 

 9.2、進(jìn)制轉(zhuǎn)換

有些時(shí)候需要作不同進(jìn)制轉(zhuǎn)換,可以參考下面的例子(%x 十六進(jìn)制,%d 十進(jìn)制,%o 十進(jìn)制)。

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

 10、Python調(diào)用系統(tǒng)命令或者腳本

使用 os.system() 調(diào)用系統(tǒng)命令 , 程序中無法獲得到輸出和返回值。

 
 
 
  1. >>> import os 
  2. >>> os.system('ls -l /proc/cpuinfo') 
  3. >>> os.system("ls -l /proc/cpuinfo") 
  4.   -r--r--r-- 1 root root 0  3月 29 16:53 /proc/cpuinfo 
  5.   0  

 使用 os.popen() 調(diào)用系統(tǒng)命令, 程序中可以獲得命令輸出,但是不能得到執(zhí)行的返回值。

 
 
 
  1. >>> out = os.popen("ls -l /proc/cpuinfo") 
  2. >>> print out.read() 
  3.   -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo   

 使用 commands.getstatusoutput() 調(diào)用系統(tǒng)命令, 程序中可以獲得命令輸出和執(zhí)行的返回值。

 
 
 
  1. >>> import commands 
  2. >>> commands.getstatusoutput('ls /bin/ls') 
  3.   (0, '/bin/ls') 

 11、Python 捕獲用戶 Ctrl+C ,Ctrl+D 事件

有些時(shí)候,需要在程序中捕獲用戶鍵盤事件,比如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" 

 12、Python 讀寫文件

一次性讀入文件到列表,速度較快,適用文件比較小的情況下

 
 
 
  1. track_file = "track_stock.conf" 
  2. fd = open(track_file) 
  3. content_list = fd.readlines() 
  4. fd.close() 
  5. for line in content_list: 
  6.     print line 

 逐行讀入,速度較慢,適用沒有足夠內(nèi)存讀取整個(gè)文件(文件太大)

 
 
 
  1. fd = open(file_path) 
  2. fd.seek(0) 
  3. title = fd.readline() 
  4. keyword = fd.readline() 
  5. uuid = fd.readline() 
  6. fd.close()   

 寫文件 write 與 writelines 的區(qū)別 。

Fd.write(str) : 把str寫到文件中,write()并不會(huì)在str后加上一個(gè)換行符。

Fd.writelines(content) : 把content的內(nèi)容全部寫到文件中,原樣寫入,不會(huì)在每行后面加上任何東西。

這篇文章主要介紹了Python語(yǔ)言的12個(gè)基礎(chǔ)知識(shí)點(diǎn)小結(jié),包含正則表達(dá)式替換、遍歷目錄方法、列表按列排序、去重、字典排序等,需要的朋友可以參考下!


新聞名稱:Python語(yǔ)言的12個(gè)基礎(chǔ)知識(shí)點(diǎn)小結(jié)
分享地址:http://www.5511xx.com/article/dpjocsg.html