歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python 基礎操作知識整理總結

Python 基礎操作知識整理總結

日期:2017/3/1 10:04:15   编辑:Linux編程
1. 數據對象持久化
在某些時候,需要將數據對象的內容保存下來,方便下次程序啟動時讀取,這個就需要將對象持久化,請看如下例子

import pickle

# create the test dictionary
before_d = {}
before_d[1]="Name 1"
before_d[2]="Name 2"
before_d[3]="Name 3"

# pickle dump the dictionary
fout = open("dict1.dat", "w")
pickle.dump(before_d, fout, protocol=0)
fout.close()

# pickle load the dictionary
fin = open("dict1.dat", "r")
after_d = pickle.load(fin)
fin.close()

print( before_d ) # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
print( after_d ) # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
可以看出,我們將數據對象內容以文件的方式保存,可以作一些簡單的cache處理,尤其是在寫一些比較小的程序時,非常有用

2. 正則表達式替換
目標: 將字符串line中的 overview.gif 替換成其他字符串

>>> line = '<IMG ALIGN="middle" SRC="overview.gif" BORDER="0" ALT="">'
>>> mo=re.compile(r'(?<=SRC=)"([\w+\.]+)"',re.I)

>>> mo.sub(r'"\1****"',line)
'<IMG ALIGN="middle" SRC="cdn_overview.gif****" BORDER="0" ALT="">'

>>> 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="testetstset" BORDER="0" ALT="">'
注意: 其中 \1 是匹配到的數據,可以通過這樣的方式直接引用

3. 遍歷目錄方法
在某些時候,我們需要遍歷某個目錄找出特定的文件列表,可以通過os.walk方法來遍歷,非常方便

import os
fileList = []
rootdir = "/tmp"
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

4. 列表按列排序(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')]
Copyright © Linux教程網 All Rights Reserved