Golang 設計模式之二工廠方法模式
阿新 • • 發佈:2020-12-26
1. 使用者傳入修改的檔名,與要修改的內容,執行函式,完成批了修改操作
def func(name, **kwargs): import os if not os.path.exists(r'{}'.format(name)): print('檔案路徑輸入錯誤') return with open(r'{}'.format(name), 'rb') as f1, \ open(r'{}.swap'.format(name), 'wb') as f2: for line in f1: line= line.decode('utf-8') if kwargs['old_content'] in line: line = line.replace(kwargs['old_content'], kwargs['new_content']) f2.write(line.encode('utf-8')) else: f2.write(line.encode('utf-8')) else: print('修改完畢') os.remove(r'{}'.format(name)) os.rename('{}.swap'.format(name), '{}'.format(name)) func('a.txt', old_content='褲衩', new_content='大褲衩')
2. 計算傳入字串中【數字】、【字母】、【空格] 以及 【其他】的個數
def func(str_ori): dic = { 'number': 0, 'letter': 0, 'space': 0, 'others': 0 }for str in str_ori: if ord(str) in range(65,91) or ord(str) in range(97,123): dic['letter'] += 1 elif str.isdigit(): dic['number'] += 1 elif ord(str) == 32: dic['space'] += 1 else: dic['others'] += 1 return(dic) res = input('請輸入查詢字串:') rec = func(res) print('數字為{},字母為{},空格為{},其他為{}'.format(rec['number'],rec['letter'],rec['space'],rec['others']))
3. 判斷使用者傳入的物件(字串、列表、元組)長度是否大於5
def func(letter, *args, **kwargs): args = list(args) print(args) print(kwargs) str_0 = '<5' list_0 = '<5' dict_0 = '<5' n = 0 while n < 3: if len(letter) > 5: str_0 = '>5' letter = '1' elif len(args) > 5: list_0 = '>5' args = [] elif len(kwargs) > 5: dict_0 = '>5' n += 1 print('字串長度{},列表長度{},字典長度{}'.format(str_0, list_0, dict_0))
4. 檢查傳入列表的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給呼叫者
def func(*args): # args = list(args) # print(args) if len(args) > 2: x,y = args[0:2] return x,y else: x,y = args return x,y x,y = func(*[1,2]) print(x,y) def morethan_two(x,y,*args): return x,y x,y = morethan_two(*[1,2,3,4,5,6]) print(x,y)
5. 檢查獲取傳入列表或元組物件的所有奇數位索引對應的元素,並將其作為新列表返回給呼叫者
def func(j): print(j,type(j)) l = [] for i in range(len(j)): if i % 2 == 0: continue else: l.append(j[i]) return l print(func([1,2,3,4,5])) print(func((1,2,3,4,5)))
6. 檢查字典的每一個value的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給呼叫者
def func(dic): for i in dic: if len(dic[i]) > 2: dic[i] = dic[i][0:2] # else: # dic[i] = dic[i] return dic dic = {"k1": "v1v1", "k2": [11, 22, 33, 44]} print(func(dic))