python之常用模塊
- 一 time模塊
- 二 random模塊
- 三 os模塊
- 四 sys模塊
- 五 json&pickle模塊
- 六 shelve模塊
- 七 re模塊
一 time模塊
Python中,表示時間的幾種方式:
1、時間戳(timestamp):時間戳表示從1970年1月1日00:00:00開始按秒計算的偏移量。運行“type(time.time())”,返回的是float類型。time.time()顯示時間戳:1487130156.419527
2、格式化的時間字符串(format_string):time.strftime("%Y-%m-%d %X")顯示:‘2017-02-15 11:40:53‘
3、結構化的時間(struct_time):struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一年中第幾周,一年中第幾天,夏令時),結構化的時間有2種如下圖:
4、常用方法:
時間戳轉換為當前時區的struct_time。secs參數未提供,則以當前時間為準。 time.localtime() time.localtime(1473525444.037215) gmtime([secs]) 和localtime()方法類似,gmtime()方法是將一個時間戳轉換為UTC時區(0時區)的struct_time。 mktime(t) : 將一個struct_time轉化為時間戳。 print(time.mktime(time.localtime()))#1473525749.0 strftime(format[, t]) : 把一個代表時間的元組或者struct_time(如由time.localtime()和 time.gmtime()返回)轉化為格式化的時間字符串。如果t未指定,將傳入time.localtime()。如果元組中任何一個 元素越界,ValueError的錯誤將會被拋出。 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56 time.strptime(string[, format]) 把一個格式化時間字符串轉化為struct_time。實際上它和strftime()是逆操作。 print(time.strptime(‘2011-05-05 16:37:06‘, ‘%Y-%m-%d %X‘)) time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,tm_wday=3, tm_yday=125, tm_isdst=-1) 在這個函數中,format默認為:"%a %b %d %H:%M:%S %Y"。 asctime([t]) : 把一個表示時間的元組或者struct_time表示為這種形式:‘Sun Jun 20 23:21:05 1993‘。 如果沒有參數,將會將time.localtime()作為參數傳入。 print(time.asctime())#Sun Sep 11 00:43:43 2016 ctime([secs]) : 把一個時間戳(按秒計算的浮點數)轉化為time.asctime()的形式。如果參數未給或者為 None的時候,將會默認time.time()為參數。它的作用相當於time.asctime(time.localtime(secs))。 print(time.ctime()) # Sun Sep 11 00:46:38 2016 print(time.ctime(time.time())) # Sun Sep 11 00:46:38 2016
二 random模塊
print(random.random())#(0,1)----float 大於0且小於1之間的小數 print(random.randint(1,3)) #[1,3] 大於等於1且小於等於3之間的整數 print(random.randrange(1,3)) #[1,3) 大於等於1且小於3之間的整數 print(random.choice([1,‘23‘,[4,5]]))#1或者23或者[4,5] print(random.sample([1,‘23‘,[4,5]],2))#列表元素任意2個組合 print(random.uniform(1,3))#大於1小於3的小數,如1.927109612082716 item=[1,3,5,7,9] random.shuffle(item) #打亂item的順序,相當於"洗牌" print(item)
三 os模塊
os使用方法:
os.getcwd() 獲取當前工作目錄,即當前python腳本工作的目錄路徑 os.chdir("dirname") 改變當前腳本工作目錄;相當於shell下cd os.curdir 返回當前目錄: (‘.‘) os.pardir 獲取當前目錄的父目錄字符串名:(‘..‘) os.makedirs(‘dirname1/dirname2‘) 可生成多層遞歸目錄 os.removedirs(‘dirname1‘) 若目錄為空,則刪除,並遞歸到上一級目錄,如若也為空,則刪除,依此類推 os.mkdir(‘dirname‘) 生成單級目錄;相當於shell中mkdir dirname os.rmdir(‘dirname‘) 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname os.listdir(‘dirname‘) 列出指定目錄下的所有文件和子目錄,包括隱藏文件,並以列表方式打印 os.remove() 刪除一個文件 os.rename("oldname","newname") 重命名文件/目錄 os.stat(‘path/filename‘) 獲取文件/目錄信息 os.sep 輸出操作系統特定的路徑分隔符,win下為"\\",Linux下為"/" os.linesep 輸出當前平臺使用的行終止符,win下為"\t\n",Linux下為"\n" os.pathsep 輸出用於分割文件路徑的字符串 win下為;,Linux下為: os.name 輸出字符串指示當前使用平臺。win->‘nt‘; Linux->‘posix‘ os.system("bash command") 運行shell命令,直接顯示 os.environ 獲取系統環境變量 os.path.abspath(path) 返回path規範化的絕對路徑 os.path.split(path) 將path分割成目錄和文件名二元組返回 os.path.dirname(path) 返回path的目錄。其實就是os.path.split(path)的第一個元素 os.path.basename(path) 返回path最後的文件名。如何path以/或\結尾,那麽就會返回空值。即os.path.split(path)的第二個元素 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) 如果path是絕對路徑,返回True os.path.isfile(path) 如果path是一個存在的文件,返回True。否則返回False os.path.isdir(path) 如果path是一個存在的目錄,則返回True。否則返回False os.path.join(path1[, path2[, ...]]) 將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略 os.path.getatime(path) 返回path所指向的文件或者目錄的最後存取時間 os.path.getmtime(path) 返回path所指向的文件或者目錄的最後修改時間 os.path.getsize(path) 返回path的大小
在Linux和Mac平臺上,該函數會原樣返回path,在windows平臺上會將路徑中所有字符轉換為小寫,並將所有斜杠轉換為飯斜杠。 >>> os.path.normcase(‘c:/windows\\system32\\‘) ‘c:\\windows\\system32\\‘ 規範化路徑,如..和/ >>> os.path.normpath(‘c://windows\\System32\\../Temp/‘) ‘c:\\windows\\Temp‘ >>> a=‘/Users/jieli/test1/\\\a1/\\\\aa.py/../..‘ >>> print(os.path.normpath(a)) /Users/jieli/test1
四 sys模塊
常用方法:
1 sys.argv 命令行參數List,第一個元素是程序本身路徑 2 sys.exit(n) 退出程序,正常退出時exit(0) 3 sys.version 獲取Python解釋程序的版本信息 4 sys.maxint 最大的Int值 5 sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 6 sys.platform 返回操作系統平臺名稱
五 json&pickle模塊
什麽是序列化?
把對象從內存中變成可存儲或傳輸的過程稱之為序列化,在Python中叫pickling,在其他語言中也被稱之為serialization
為什麽要序列化?
1:持久保存狀態
2:跨平臺數據交互
序列化對象後,可以把序列化後的內容寫入磁盤,也可以通過網絡傳輸到別的機器上,如果收發的雙方約定好實用一種序列化的格式,便打破了平臺/語言差異化帶來的限制,實現了跨平臺數據交互。
反過來,把變量內容從序列化的對象重新讀到內存裏稱之為反序列化,即unpickling。
如何序列化之json和pickle:
json
不同的編程語言之間傳遞對象,必須把對象序列化為標準格式,比如XML,但更好的方法是序列化為JSON,因為JSON表示出來就是一個字符串,可以被所有語言讀取,也可以方便地存儲到磁盤或者通過網絡 傳輸。JSON不僅是標準格式,並且比XML更快,而且可以直接在Web頁面中讀取,非常方便。
JSON表示的對象就是標準的JavaScript語言的對象。
六 shelve模塊
shelve只有一個open函數,返回類似字典,可讀可寫;key必須為字符串,而值可以是python所支持的數據類型
import shelve f=shelve.open(r‘abc.txt‘) # f[a‘]={‘name‘:‘Andy,‘age‘:18} # f[‘b]={‘name‘:‘axle‘,‘age‘:53} # f[‘v‘]={‘website‘:‘http://www.pypy.org‘,‘city‘:‘beijing‘} print(f[‘a‘][‘name‘]) f.close()
十三 re模塊
一:什麽是正則?
正則就是用一些具有特殊含義的符號組合到一起(稱為正則表達式),用於描述字符或者字符串的方法。它內嵌在Python中,並通過 re 模塊實現。正則表達式模式被編譯成一系列的字節碼,然後由用 C 編寫的匹 配引擎執行。
二:常用匹配模式(元字符)
import re #\w匹配字母數字下劃線 \W匹配非字母下劃線 # print(re.findall(‘\w‘,‘hello engon 123‘)) # print(re.findall(‘\W‘,‘hello engon 123 \n \t‘)) #\s匹配任意空白字符[\n\t\r] \S匹配任意非空白字符 # print(re.findall(‘\s‘,‘hello engon 123‘)) # print(re.findall(‘\S‘,‘hello engon 123‘)) #\d匹配數字,任意數字[0-9]\D匹配任意非數字 # print(re.findall(‘\d‘,‘hello engon 123‘)) # print(re.findall(‘\D‘,‘hello engon 123‘)) #匹配字符開始\A或^ # print(re.findall(‘\Ahe‘,‘hello engon 123‘)) # print(re.findall(‘^he‘,‘hello engon 123‘)) #匹配字符結束$或\Z # print(re.findall(‘3\Z‘,‘hello engon 123‘)) # print(re.findall(‘he$‘,‘hello engon 123‘)) # 重復匹配:| . | * | ? | .* | .*? | + | {n,m} | #.匹配任意字符,除了換行符,當re.DOTALL或re.S標記被指定時,則可以匹配換行符的任意字符 # print(re.findall(‘a.b‘,‘a|b‘)) # print(re.findall(‘a.b‘,‘a1b a*b a b aaab‘)) # print(re.findall(‘a.b‘,‘a\nb‘)) # print(re.findall(‘a.b‘,‘a\nb‘,re.S)) # print(re.findall(‘a.b‘,‘a\nb‘,re.DOTALL)) #*匹配0個或多個的表達式 # print(re.findall(‘ab*‘,‘bbbbbbb‘)) # print(re.findall(‘a*‘,‘a‘)) # print(re.findall(‘ab*‘,‘abbbbbbb‘)) #?匹配0個或一個 # print(re.findall(‘ab?‘,‘a‘)) # print(re.findall(‘ab?‘,‘abbb‘)) #匹配所有包含小數在內的數字 # print(re.findall(‘\d+\.?\d‘,"asdfasdf123as1.13dfa12adsf1asdf3")) #.*默認為貪婪匹配 # print(re.findall(‘a.*b‘,‘a1b22222222b‘)) #.*?為非貪婪匹配:推薦使用 # print(re.findall(‘a.*?b‘,‘a1b2222222222b‘)) #+匹配一個或多個的表達式 # print(re.findall(‘ab+‘,‘a‘)) # print(re.findall(‘ab+‘,‘abbbb‘)) #{n,m} # print(re.findall(‘ab{2}‘,‘abbb‘)) # print(re.findall(‘ab{2,3}‘,‘abbbbbbb‘)) # print(re.findall(‘ab{1,}‘,‘abbbbbbbbbbbbbb‘)) # print(re.findall(‘ab{0,}‘,‘abbbbbbbbbbbbb‘)) #[] # print(re.findall(‘a[1*-]b‘,‘a1b a*b a-b‘)) # #頭或尾 # print(re.findall(‘a[^1*-]‘,‘a1b a*b a-b a=b‘)) # print(re.findall(‘a[0-9]b‘,‘a1b a*b a-b a=b‘)) # print(re.findall(‘a[a-z]b‘,‘a1b a*b a-b a=b aeb‘)) # print(re.findall(‘a[a-zA-Z]b‘,‘a1b a*b a-b a=b aeb aEb‘)) # print(re.findall(‘a\\\c‘,‘a\c‘)) # print(re.findall(r‘a\\c‘,‘a\c‘)) # print(re.findall(‘a\\\\c‘,‘a\c‘)) #():分組 # print(re.findall(‘ab+‘,‘ababab123‘)) # print(re.findall(‘(ab)+123‘,‘ababab123‘)) # print(re.findall(‘(?:ab)+123‘,‘ababab123‘)) # print(re.findall(‘compan(?:y|ies)‘,‘Too many companies have gone bankrupt, and the next one is my company‘)) #re的其它方法 #直到找到第一個匹配然後返回一個包含匹配信息的對象,該對象可以通過調用group()方法得到匹配的字符竄,如果字符竄沒有匹配成功,則返回None # print(re.search(‘e‘,‘alex make love‘).group()) #只找開始處,匹配到返回,匹配不到返回None # print(re.match(‘1‘,‘alex make love‘)) #先按‘a‘分割到‘‘和‘bcd‘,再對‘‘和‘bcd‘分別按‘b‘進行分割 # print(re.split(‘[ab]‘,‘abcd‘)) # print(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘)) # print(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘,1)) # print(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘,2)) # print(‘===>‘,re.sub(‘^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$‘,r‘\5\2\3\4\1‘,‘alex make love‘)) # print(‘===>‘,re.sub(‘^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$‘,r‘\5\2\3\4\1‘,‘alex make love‘)) #6 # obj=re.compile(‘\d{2}‘) # print(obj.findall(‘abc123eeee‘)) #此處就是通過 (?P=name)的方式,來引用,正則表達式中,前面已經命名tagName的group的 # print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) # print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<111>hello</111>")) # print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").group()) # # # # print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").groupdict()) # # # print(re.search(r"<(\w+)>\w+</(\w+)>","<h1>hello</h1>").group()) # print(‘===>>‘,re.search(r"<(\w+)>(\w+)</\1>","<h1>hello</h1>").group()) print(re.findall(r‘-?\d+\.*\d*‘,"1-12*(60+(-40.35/5)-(-4*3))")) #找出所有數字[‘1‘, ‘-12‘, ‘60‘, ‘-40.35‘, ‘5‘, ‘-4‘, ‘3‘] print(re.findall(r"-?\d+\.\d+/\d+\.*\d+\.*\d+","1-2*(60+(-40.35/5)-(-4*3))"))
python之常用模塊