python基礎(3)

來源:互聯網
上載者:User

標籤:dev   move   函數   分組   表示   data   刪除目錄   timestamp   count   

普通裝飾器

# (@+函數名),需要記住關鍵兩點:
#功能:
#1、自動執行outer函數,並且將其下面的函數名f1當作參數傳遞
#2、將outer函數的傳回值,重新賦值給f1

# #裝飾器必備
# ####第一:函數名和執行函數####
# def foo(): #建立函數
# print(‘hello‘) #函數體
# foo #表示是函數名,代指整個函數
# foo() #表示執行f00函數
# # 輸出:hello

# ####第二:函數被重新定義###
# def foo():
# print("foo1")
#
# foo = lambda : print("foo2") #lambda運算式,無參數
#
# foo() #執行下面的lambda運算式,而不是原來的foo函數,foo函數已經被重新定義

常用模組time模組time.time()
import timeimport datetimeprint(time.time()) # 返回目前時間的時間戳記
time.ctime()
print(time.ctime()) # 將時間戳記轉化為字串格式Wed Feb 17 11:41:27 2016,預設是當前系統時間的時間戳記print(time.ctime(time.time()-3600)) # ctime可以接收一個時間戳記作為參數,返回該時間戳記的字串形式 Wed Feb 17 10:43:04 2016
time.gtime()
print(time.gmtime()) # 將時間戳記轉化為struct_time格式,預設是當前系統時間戳print(time.gmtime(time.time() - 3600))
time.localtime()
print(time.localtime()) # 同樣是將時間戳記轉化為struct_time,只不過顯示的是本地時間,gmtime顯示的是標準時間(格裡尼治時間)
time.mktime()
print(time.mktime(time.localtime())) # 將struct_time時間格式轉化為時間戳記
time.strftime()
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 將struct_time時間格式轉化為自訂的字串格式
time.trptime()
print(time.strptime("2016-02-17", "%Y-%m-%d")) # 與trftime相反,將字串格式轉化為struct_time格式
time.asctime()
print(time.asctime(time.localtime())) # 將struct_time轉化為字串形式
datetime模組
  • datetime.date:表示日期的類。常用的屬性有year, month, day
  • datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond
  • datetime.datetime:表示日期時間
  • datetime.timedelta: 表示時間間隔,即兩個時間點之間的長度
datetime.date.today()
print(datetime.date.today()) # 返回當前日期的字串形式2016-02-17
datetime.date.fromtimestamp()
print(datetime.date.fromtimestamp(time.time() - 3600 * 24)) # 將時間戳記轉化為日期文字形式2016-02-16
datetime.datetime.now()
print(datetime.datetime.now()) # 返回的時間的字串形式2016-02-17 13:53:30.719803print(datetime.datetime.now().timetuple()) # 轉化為struct_time格式
datetime.timedelta()

datetime.timedelta()返回的是一時間間隔對象,常與datetime.datetime.now()合用計算時間

print(datetime.datetime.now() - datetime.timedelta(days = 2))
random模組

random模組主要用來產生隨機數

random()

產生大於0小於1的浮點類型隨機數

print(random.random()) #產生大於0小於1的浮點類型隨機數
序列化

Python中用於序列化的兩個模組

  • json     用於【字串】和 【python基礎資料型別 (Elementary Data Type)】 間進行轉換
  • pickle   用於【python特有的類型】 和 【python基礎資料型別 (Elementary Data Type)】間進行轉換

Json模組提供了四個功能:dumps、dump、loads、load

pickle模組提供了四個功能:dumps、dump、loads、load

os模組

提供對作業系統進行調用的介面

>>> import os>>> os.getcwd() # 擷取當前工作目錄,類似linux的pwd命令‘/data/python/day5‘>>> os.chdir(‘..‘) # 進入某個目錄,類似linux的cd命令>>> os.getcwd() ‘/data/python‘>>> os.curdir # 擷取目前的目錄‘.‘>>> os.pardir # 擷取目前的目錄的父目錄‘..‘>>> os.chdir(‘day5‘)>>> os.getcwd()‘/data/python/day5‘>>> os.makedirs(‘testdir1/testdir2‘) # 遞迴建立目錄相當於 mkdir -p命令>>> os.makedirs(‘test_dir1/test_dir2‘) # 遞迴建立目錄相當於 mkdir -p命令>>> os.listdir(‘.‘) # 顯示目錄下多所有檔案 相當於linux的ls -a[‘test_dir1‘]>>> os.removedirs(‘test_dir1/test_dir2‘) # 刪除多級(遞迴)目錄,注意目錄必須是空的,若目錄為空白刪除,並遞迴到上以及目錄,如果也為空白則也刪除>>> os.mkdir(‘test2‘) # 建立目錄,相當於mkdir>>> os.rmdir(‘test2‘) # 刪除目錄,相當於rm>>> f = open(‘test.txt‘, ‘w‘)>>> f.write(‘testline‘)8>>> f.close()>>> os.listdir()             [‘testdir2‘, ‘test.txt‘, ‘testdir1‘]>>> os.rename(‘test.txt‘, ‘new_test.txt‘) #重新命名>>> os.stat(‘.‘) # 顯示目錄或檔案的狀態,包括許可權等os.stat_result(st_mode=16877, st_ino=786731, st_dev=64784, st_nlink=4, st_uid=0, st_gid=0, st_size=4096, st_atime=1455695375, st_mtime=1455696066, st_ctime=1455696066)>>> os.sep # 擷取檔案分割符,linux為/,windows為\‘/‘>>> os.name # 返回平台名,linux為posix,win為nt‘posix‘>>> os.linesep # 返回系統分行符號,win下為\r\n‘\n‘>>> os.pathsep # 返回用於分割檔案路徑的字串,vin下為;‘:‘>>> os.system(‘ls‘) # 執行shell命令testdir1  testdir20>>> os.environ # 擷取系統內容變數environ({‘USER‘: ‘root‘, ‘PATH‘: ‘/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin‘, ‘SHELL‘: ‘/bin/bash‘, ‘HOME‘: ‘/root‘, ‘SHLVL‘: ‘1‘, ‘HISTTIMEFORMAT‘: ‘%...省略n多好...>>> os.path.abspath(‘.‘) # 返回目錄的絕對路徑‘/data/python/day5‘>>> os.path.split(‘/data/python/day5‘) # 將path分割成目錄和檔案,元祖返回(‘/data/python‘, ‘day5‘) >>> os.path.dirname(‘/data/python/day5‘) # 返回path也即是split的第一個元素‘/data/python‘>>> os.path.basename(‘/data/python/day5‘) # 返迴文件名也即是split的第一個元素‘day5‘ >>> os.path.exists(‘/data/python/day5‘) # 判斷目錄或檔案是否存在True>>> os.path.isabs(‘/data/python/day5‘) # 判斷是否是絕對目錄,不考慮是否存在,說白了就是字串符合絕對路徑的規範就返回TrueTrue>>> os.path.isabs(‘day5‘)          False>>> os.path.isabs(‘/data/python/day6‘) # True>>> os.path.isfile(‘/data/python/day5‘) # 判斷是否是檔案False>>> os.path.isdir(‘/data/python/day5‘) # 判斷是否是目錄True>>> os.path.isdir(‘/data/python/day6‘)False>>> os.path.join(‘/data/python/day6‘, ‘test‘) # 組合目錄‘/data/python/day6/test‘>>> os.path.getatime(‘/data/python/day5‘) # 返迴文件或目錄的最後訪問時間1455695375.9394312>>> os.path.getmtime(‘/data/python/day5‘) # 返迴文件或目錄的最後修改時間1455696066.0034554>>> os.path.getctime(‘/data/python/day5‘) # 返迴文件或目錄的建立時間1455696066.0034554

 

Regex

 字串是編程時涉及到的最多的一種資料結構,對字串進行操作的需求幾乎無處不在。比如判斷一個字串是否是合法的Email地址,雖然可以編程提取@前後的子串,再分別判斷是否是單詞和網域名稱,但這樣做不但麻煩,而且代碼難以複用。

    Regex是一種用來匹配字串的強有力的武器。它的設計思想是用一種描述性的語言來給字串定義一個規則,凡是符合規則的字串,我們就認為它“匹配”了,否則,該字串就是不合法的。    下面這張圖展示了使用Regex匹配的流程python的re模組

Python通過re模組提供對Regex的支援。使用re的一般步驟是先將Regex的字串形式編譯為Pattern執行個體,然後使用Pattern執行個體處理文本並獲得匹配結果(一個Match執行個體),最後使用Match執行個體獲得資訊,進行其他的操作。

import re # 將Regex編譯成Pattern對象pattern = re.compile(r‘hello‘) # 使用Pattern匹配文本,獲得匹配結果,無法匹配時將返回Nonematch = pattern.match(‘hello world!‘)  if match:    # 使用Match獲得分組資訊    print match.group()
re模組的常用方法re.compile(strPattern[, flag])    參數:        strPattern:Regex        flag:匹配模式,可選值有            re.I(re.IGNORECASE): 忽略大小寫(括弧內是完整寫法,下同)            M(MULTILINE): 多行模式,改變‘^‘和‘$‘的行為(參見)            S(DOTALL): 點任意匹配模式,改變‘.‘的行為            L(LOCALE): 使預定字元類 \w \W \b \B \s \S 取決於目前範圍設定            U(UNICODE): 使預定字元類 \w \W \b \B \s \S \d \D 取決於unicode定義的字元屬性            X(VERBOSE): 詳細模式。這個模式下Regex可以是多行,忽略空白字元,並可以加入注釋。    傳回值:Pattern對象是一個編譯好的Regex,通過Pattern提供的一系列方法可以對文本進行匹配尋找    以下的方法既可以是Pattern對象的執行個體方法也可以是re模組的方法,文法稍有不同match(string[, pos[, endpos]]) | re.match(pattern, string[, flags])    這個方法將從string的pos下標處起嘗試匹配pattern;如果pattern結束時仍可匹配,則返回一個Match對象;如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。    pos和endpos的預設值分別為0和len(string);re.match()無法指定這兩個參數,參數flags用於編譯pattern時指定匹配模式。    注意:這個方法並不是完全符合。當pattern結束時若string還有剩餘字元,仍然視為成功。想要完全符合,可以在運算式末尾加上邊界匹配符‘$‘。     參數:    string:要匹配的字串    pos:匹配的開始下標    endpos:匹配的結束下標    pattern:Regex    flags:匹配模式    傳回值:如果匹配成功返回match對象,否則返回Nonesearch(string[, pos[, endpos]]) | re.search(pattern, string[, flags])    這個方法用於尋找字串中可以匹配成功的子串。從string的pos下標處起嘗試匹配pattern,如果pattern結束時仍可匹配,則返回一個Match對象;若無法匹配,則將pos加1後重新嘗試匹配;直到pos=endpos時仍無法匹配則返回None。pos和endpos的預設值分別為0和len(string));re.search()無法指定這兩個參數,參數flags用於編譯pattern時指定匹配模式。     參數:同match    傳回值:同match     我們通過一個執行個體來看一下兩個方法的區別
>>> import re>>> s = ‘hello world‘>>> print(re.match(‘ello‘, s))None>>> print(re.search(‘ello‘,s ))<_sre.SRE_Match object; span=(1, 5), match=‘ello‘>    說明:可以看到macth只匹配開頭,開頭不匹配,就不算匹配到,search則可以從中間,只要能有匹配到就算匹配findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags])    搜尋string,以列表形式返回全部能匹配的子串。有點像search的擴充,把所有匹配的子串放到一個列表    參數:同match    傳回值:所有匹配的子串,沒有匹配則返回空列表>>> import re             >>> s = ‘one1two2three3four4‘>>> re.findall(‘\d+‘, s)[‘1‘, ‘2‘, ‘3‘, ‘4‘]
split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):    按照匹配字子串將字串進行分割,返回分割收的列表    參數:     string:要分割的字串     pattern:Regex    maxsplit:最大分割次數    傳回值:分割後的列表    執行個體
>>> import re                 >>> s = ‘one1two2three3four4‘>>> re.split(‘\d+‘, s)[‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘‘]
sub(repl, string[, count]) | re.sub(pattern, repl, string[, count])    使用repl替換string中匹配的每一子串    參數:    repl:替換的字串或方法,這裡需要說一下這個方法,方法接收macth對象,方法的傳回值作為替換的字串,換句話就是經過處理的字串。    string:要進行替換的字串    pattern:Regex    count:替換的次數    執行個體:對於repl是個方法的情況,正好這次作業用到,用來替換多個則很難過福號的情況。假設我們有一個四則運算運算式 ‘--(1.1+1+1-(-1)-(1+1+(1+1+2.2)))+-----111+--++--3-+++++++---+--- 1+4+4/2+(1+3)*4.1+(2-1.1)*2/2*3‘,遵循奇數個負號等於正否則為負的原則進行替換,我們可以這樣
if __name__ == ‘__main__‘:    import re    s = ‘--(1.1+1+1-(-1)-(1+1+(1+1+2.2)))+-----111+--++--3-+++++++---+---1+4+4/2+(1+3)*4.1+(2-1.1)*2/2*3‘    def replace_sign(expression):        ‘‘‘        替換多個連續+-符號的問題,例如+-----,遵循奇數個負號等於正否則為負的原則進行替換        :param expression: 運算式,包括有括弧的情況        :return: 返回經過處理的運算式        ‘‘‘        def re_sign(m):            if m:                if m.group().count(‘-‘)%2 == 1:                    return ‘-‘                else:                    return ‘+‘            else:                return ‘‘        expression = re.sub(‘[\+\-]{2,}‘, re_sign, expression)        return expression     s = replace_sign(s)    print(s)

執行結果

24 +(1.1+1+1-(-1)-(1+1+(1+1+2.2)))-111+3-1+4+4/2+(1+3)*4.1+(2-1.1)*2/2*3

python基礎(3)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.