python編程中常用的12種基礎知識總結:正則表達式替換,遍歷目錄方法,列表按列排序、去重,字典排序,字典、列表、字符串互轉,時間對象操作,命令行參數解析(getopt),print 格式化輸出,進制轉換,Python調用系統命令或者腳本,Python 讀寫文件。
1、正則表達式替換
目標: 將字符串line中的 overview.gif 替換成其他字符串
代碼如下:>>> line = '<IMG ALIGN="middle" SRC=/'#/'" />'
>>> 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])
新聞熱點
疑難解答