1. 程式人生 > >luffy-chapter1-unit3-文件操作&函數 review

luffy-chapter1-unit3-文件操作&函數 review

ber cme 類型 odi info chapter utf8 其他 insert

文件處理相關

1、編碼問題

(1)請說明python2 與python3中的默認編碼是什麽?

py2默認ASCII碼,py3默認的utf8

(2)為什麽會出現中文亂碼?你能列舉出現亂碼的情況有哪幾種?

用什麽格式編碼,就需要用什麽格式解碼

#coding:utf-8 #.py文件是什麽編碼就需要告訴python用什麽編碼去讀取這個.py文件。
sys.stdout.encoding,默認就是locale的編碼,print會用sys.stdout.encoding去encode()成字節流,交給terminal顯示。所以locale需要與terminal一致,才能正確print打印出中文。
sys.setdefaultencoding(‘utf8’),用於指定str.encode() str.decode()的默認編碼,默認是ascii。
以下幾種(local 為軟件運行時的語言環境):
 終端為UTF
-8,locale為zh_CN.GBK 終端為UTF-8,locale為zh_CN.UTF-8 終端為GBK,locale為zh_CN.GBK 終端為GBK,locale為zh_CN.UTF-8

(3)如何進行編碼轉換?

字符串在python內部中是采用unicode的編碼方式,所以其他語言先decode轉換成unicode編碼,再encode轉換成utf8編碼。

(4)#-*-coding:utf-8-*- 的作用是什麽?

編碼聲明

(5)解釋py2 bytes vs py3 bytes的區別

  Python 2 將 strings 處理為原生的 bytes 類型,而不是 unicode(python2 str == bytes),

   Python 
3 所有的 strings 均是 unicode 類型(python3 中需要通過 unicode ) string -> encode -> bytes bytes -> decode -> string

2、文件處理

r和rb的區別是什麽?
r 只讀模式
rb 二進制只讀模式
解釋一下以下三個參數的分別作用
 open(f_name,r,encoding="utf-8")
f_name   文件名
 r      模式
encoding  編碼方式

函數基礎:

1、寫函數,計算傳入數字參數的和(動態傳參)

# 函數基礎:

# 
1、寫函數,計算傳入數字參數的和。(動態傳參) # def sum(x,y): # return x+y # # print(sum(2,3)) # # #美 /l?md?/ 匿名函數 # sum = lambda x,y:x+y # print(sum(2,3)) # 2、寫函數,用戶傳入修改的文件名,與要修改的內容,執行函數,完成整個文件的批量修改操作 # 修改列表中字符串首字母大寫 # def modify_file(a): # file = open(a, r+, encoding=utf-8) # data_list = [] # f = file.readlines() # print(len(f)) # for line in f: # # 修改後必須賦值否則無效 # line = line.capitalize() # data_list.append(line) # file.seek(0) # file.truncate() # for line in data_list: # file.write(line) # file.close() # modify_file(test.txt) # capitalize() 函數補充 # # 需要註意的是: # # 1、首字符會轉換成大寫,其余字符會轉換成小寫。 # # 2、首字符如果是非字母,首字母不會轉換成大寫,會轉換成小寫,其余也轉化為小寫。 # 3、寫函數,檢查用戶傳入的對象(字符串、列表、元組)的每一個元素是否含有空內容。 # def check(a): # if type(a) == str: # if len(a) == 0: # print(字符串為空) # # check_out = [] # for i in a: # if i == ‘‘: # i = # check_out.append(i) # if type(a) ==tuple: # print(tuple(check_out)) # elif type(a) ==list: # print(check_out) # # need_check_str = ‘‘ # check(need_check_str) # # need_check_list = [a,b,1,‘‘,q] # check(need_check_list) # # need_check_tuple = (1,2,‘‘,qq) # check(need_check_tuple) # 4、寫函數,檢查傳入字典的每一個value的長度,如果大於2,那麽僅保留前兩個長度的內容,並將新內容返回給調用者。 #PS:字典中的value只能是字符串或列表 # dic = {"k1": "v1v1", "k2": [11,22,33,44]} # def check_dict(a): # for k,v in a.items(): # if len(v) > 2: # a[k] = v[0:2] # return a # # b = check_dict(dic) # print(b) # 5 解釋閉包的概念 # 閉包(closure) # 是函數式編程的重要的語法結構。函數式編程是一種編程範式(而面向過程編程和面向對象編程也都是編程範式)。 # 在面向過程編程中,我們見到過函數(function);在面向對象編程中,我們見過對象(object)。 # 函數和對象的根本目的是以某種邏輯方式組織代碼,並提高代碼的可重復使用性(reusability)。 # 閉包也是一種組織代碼的結構,它同樣提高了代碼的可重復使用性。 #函數進階: #例如:[(‘紅心’,2),(‘草花’,2), …(‘黑桃A’)] # 1、寫函數,返回一個撲克牌列表,裏面有52項,每一項是一個元組 # 方塊,梅花,紅心,黑桃 # def playing_card(): # playing_card_list = [] # color = [方塊,梅花,紅心,黑桃] # card = [J,Q,K,A] # for i in range(2,11): # card.insert(i-2,i) # for index in card: # for j in color: # playing_card_list.append((j,index)) # #print(playing_card_list) # return playing_card_list # playing_card() # print(playing_card()) # 2、文件處理 # 寫函數,傳入n個數,返回字典{‘max’:最大值,’min’:最小值} # 例如:min_max(2,5,7,8,4) # 返回:{‘max’:8,’min’:2} # def max_min(a): # dict = {} # dict[max] = max(a) # dict[min] = min(a) # return dict # s = [2,3,6,4,3,-100] # print(max_min(s)) # 3、寫函數,專門計算圖形的面積 # 其中嵌套函數,計算圓的面積,正方形的面積和長方形的面積 # # 調用函數area(‘圓形’,圓半徑) 返回圓的面積 # 調用函數area(‘正方形’,邊長) 返回正方形的面積 # 調用函數area(‘長方形’,長,寬) 返回長方形的面積 # *args 返回是元組的形式 # (長方形的面積為:, 12) # (圓的面積為:, 28.274333882308138) # (正方形的面積為:, 9) # import math # def area(name,*args): # def areas_rectangle(x,y): # return "長方形的面積為:",x*y # def area_square(x): # return "正方形的面積為:",x**2 # def area_round(r): # return 圓的面積為:,math.pi*r*r # if name == rectangle: # return areas_rectangle(*args) # if name == square: # return area_square(*args) # if name == round: # return area_round(*args) # print(area(rectangle, 3, 4)) # print(area(round, 3)) # print(area(square, 3)) # 4、寫函數,傳入一個參數n,返回n的階乘 # 例如:cal(7) # 計算7*6*5*4*3*2*1 # def cal(nmuber): # s = 1 # for i in range(1,nmuber+1): # s = s*i # return s # print(cal(5)) # 遞歸函數法 # def cal(nmuber): # # if nmuber == 1: # return 1 # else: # return nmuber*cal(nmuber-1) # print(cal(4)) # 5、編寫裝飾器,為多個函數加上認證的功能(用戶的賬號密碼來源於文件),要求登錄成功一次,後續的函數都無需再輸入用戶名和密碼 #dict_file = eval(file) # 字符串轉為字典 # user_status = False # def login(func): # def inner(*args,**kwargs): # global user_status # # while True: # if user_status == False: # username = input(name:>).strip() # password = input(password:>).strip() # with open(user_info.txt,r+,encoding=utf-8) as f: # userinfo = f.read().strip() # userinfo = eval(userinfo) # print(userinfo) # if username in userinfo[name] and password == userinfo[password]: # print(-------welcome-------) # user_status = True # break # else: # print(name or password wrong) # continue # # if user_status == True: # return func(*args, **kwargs) # return inner() # # # # @login # # def home(): # # print(-----首頁-----) # # home() # @login # def japan(): # print(----daoguo-----) # japan() # # # # def login(func): # def wrapper(*args,**kwargs): # username = input("account:").strip() # password = input("password:").strip() # with open(user_info.txt,r,encoding=utf-8) as f: # userinfo = f.read().strip(,) # userinfo = eval(userinfo) # print(userinfo) # if username in userinfo[name] and password in userinfo[password]: # print("success") # else: # print("pass") # # return wrapper # # @login # def name(): # print("hello") # # name() # 生成器和叠代器 # 1 # 生成器和叠代器的區別? # list = [1,2,34,5] # it = iter(list) # print(next(it)) # print(next(it)) # print(next(it)) # 2 生成器generator有幾種方式獲取value? # 兩種方式獲取: # for 循環 # next 獲取 import sys # def fib(max): # n,a,b = 0,0,1 # # while n < max: # #print(b) # yield b # a,b = b,a+b # n += 1 # return done # g = fib(10) # # while True: # try: # x = next(g) # print(g:,x) # except StopIteration as e: # print(generator return value:,e.value) # break # # 普通函數 生成器函數 - 斐波那契 # def fib(max): # n,a,b = 0,0,1 # # while n < max: # print(b) # #yield b # a,b = b,a+b # n += 1 # return done # fib(10) # 內置函數 # 1 用map來處理字符串列表,把列表中所有人都變成sb,比方alex_sb # name=[alex,wupeiqi,yuanhao,nezha] # def change(x): # return x+_nice # print(map(change,name)) # # print(list(map(lambda x:x+_nice,name))) # 2、用filter函數處理數字列表,將列表中所有的偶數篩選出來 # num = [1,3,5,6,7,8] # def choice(x): # if x %2 == 0: # return x # ret = filter(choice,num) # print(list(ret)) # print(list(filter(lambda x:x%2==0,num))) # 3 如下,每個小字典的name對應股票名字,shares對應多少股,price對應股票的價格 portfolio = [ {name: IBM, shares: 100, price: 91.1}, {name: AAPL, shares: 50, price: 543.22}, {name: FB, shares: 200, price: 21.09}, {name: HPQ, shares: 35, price: 31.75}, {name: YHOO, shares: 45, price: 16.35}, {name: ACME, shares: 75, price: 115.65}, ] # 計算購買每支股票的總價 # # 用filter過濾出,單價大於100的股票有哪些 for index in range(len(portfolio)): print(f"{portfolio[index][‘name‘]}的股票總價為:{portfolio[index][‘shares‘]*portfolio[index][‘price‘]}") for index in range(len(portfolio)): if portfolio[index][price] > 100: print(股票單價大於100的有:,portfolio[index][name]) f = filter(lambda d: d[price] >= 100, portfolio) print(list(f))

luffy-chapter1-unit3-文件操作&函數 review