python核心編程第二版第9章習題答案_第1頁
python核心編程第二版第9章習題答案_第2頁
python核心編程第二版第9章習題答案_第3頁
python核心編程第二版第9章習題答案_第4頁
python核心編程第二版第9章習題答案_第5頁
已閱讀5頁,還剩34頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、91. 文件過濾. 顯示一個文件的所有行, 忽略以井號( # )開頭的行. 這個字符被用做Python , Perl, Tcl, 等大多腳本文件的注釋符號.附加題: 處理不是第一個字符開頭的注釋.答案:f = open(test1.txt,r)for eachline in f:if eachline0 = #:continueelif # in eachline:loc = eachline.find(#)print eachline:locelse:print eachline,92. 文件訪問. 提示輸入數(shù)字 N 和文件 F, 然后顯示文件 F 的前 N 行.答案:N = int(raw

2、_input(Enter a number: )f = raw_input(Enter filename :)f1 = open(f,r)allline = f1.readlines()f1.close()for i in range(N):print alllinei,93. 文件信息. 提示輸入一個文件名, 然后顯示這個文本文件的總行數(shù).答案:f = raw_input(Enter filename :)f1 = open(f,r)sum = 0for i in f1:sum += 1print sumf = raw_input(Enter filename :)f1 = open(f,r

3、)sum = 0for i in f1:sum += 1print sum方法二:f = raw_input(Enter filename :)f1 = open(f,r)allline = f1.readlines()f1.close()print len(allline)94. 文件訪問. 寫一個逐頁顯示文本文件的程序. 提示輸入一個文件名, 每次顯示文本文件的 25 行, 暫停并向用戶提示按任意鍵繼續(xù)., 按鍵后繼續(xù)執(zhí)行.答案:f = raw_input(Enter filename :)f1 = open(f,r)allline = f1.readlines()f1.close()su

4、m = 0for i in allline:print i,sum += 1if sum = 25:a = raw_input(press any key to continue:)sum = 0方法二import os F=raw_input(pls input a file name:) n=0 f=open(F,r) for i in f: print i, n+=1 if n=25: n=0 os.system(pause) f.close() 9-5 考試成績,改進你的考試成績問題(練習5-3和6-4),要求能從多個文件中讀入考試成績。文件的數(shù)據(jù)格式由你自己決定。答案:f = ope

5、n(test1.txt,r)scores = for i in f:if 0 = int(i.strip()= 100:scores.append(int(i.strip()else:print score wrong ,please againif int(i.strip() 60:print score is E,ielif int(i.strip() 70:print score is D,ielif int(i.strip() 80:print score is C,ielif int(i.strip() 90:print score is B,ielse:print score is

6、 A,if.close()print average score is %.2f % (sum(scores)/len(scores)96. 文件比較. 寫一個比較兩個文本文件的程序. 如果不同, 給出第一個不同處的行號和列號.答案:f1 = raw_input(Enter a filename: )f2 = raw_input(Enter a filename: )F1 = open(f1,r)F2 = open(f2,r)F1allline = F1.readlines()F2allline = F2.readlines()F1.close()F2.close()len1 = len(F1

7、allline)len2 = len(F2allline)minlen1 = min(len1,len2)for i in range(minlen1):print F1alllinei, F2alllineiif F1alllinei != F2alllinei:minlen2 = min(len(F1alllinei),len(F2alllinei)for j in range(minlen2):if F1alllineij != F2alllineij:print row is %d, column is %d % (i+1,j+1)breakelse:continueelse:prin

8、t they are equaln97. 解析文件. Win32 用戶: 創(chuàng)建一個用來解析 Windows .ini 文件的程序. POSIX 用戶:創(chuàng)建一個解析 /etc/serves 文件的程序. 其它平臺用戶: 寫一個解析特定結(jié)構(gòu)的系統(tǒng)配置文件的程序.答案:這題沒看懂,抄的別人option = f = open(rc:windowswin.ini)for line in f:if line.startswith(;):continueif line.startswith():iterm = name = line1:line.rfind()option.setdefault(name,i

9、term)continueif = in line:optionname.append(line.strip()print option98. 模塊研究. 提取模塊的屬性資料. 提示用戶輸入一個模塊名(或者從命令行接受輸入).然后使用 dir() 和其它內(nèi)建函數(shù)提取模塊的屬性, 顯示它們的名字, 類型, 值.答案:m = raw_input(Enter a module name: )module = _import_(m)m1 = dir(module)print m1for i in m1:print name:,iprint tyoe:,type(getattr(module,i)pri

10、nt value:,getattr(module,i)print99. Python文檔字符串。進入Python標準庫所在的目錄。檢查每個 .py 文件看是否有_doc_ 字符串, 如果有, 對其格式進行適當?shù)恼須w類. 你的程序執(zhí)行完畢后, 應(yīng)該會生成一個漂亮的清單. 里邊列出哪些模塊有文檔字符串, 以及文檔字符串的內(nèi)容. 清單最后附上那些沒有文檔字符串模塊的名字.附加題: 提取標準庫中各模塊內(nèi)全部類(class)和函數(shù)的文檔.答案:這是入口#coding:utf-8import osimport sysnum = 將所有路徑文件名全部提取出來def fun(dirName):for i i

11、n os.listdir(dirName):if os.path.isdir(dirName + + i):fun(dirName + + i)else:num.append(dirName + + i)fun(rc:python27Lib)hasDoc = FalsestrTemp = fileobj1 = open(hasdoc.txt,a+)fileobj2 = open(nodoc.txt,a+)for i in num:print ifobj = open(i)for eachline in fobj:if (not hasDoc) and eachline.startswith()

12、:hasDoc = Trueelif hasDoc and eachline.startswith():hasDoc = FalsestrTemp += eachlinebreakif hasDoc:strTemp += eachlineelse:breakif strTemp != :fileobj1.write(filename: + i + n)fileobj1.write(_doc_ + n)fileobj1.write(strTemp + n)else:fileobj2.write(文件名: + i + n)strTemp = fobj.close()fileobj1.close()

13、fileobj2.close()9-10.家庭理財。創(chuàng)建一個家庭理財程序。你的程序需要處理儲蓄、支票、金融市場,定期存款等多種賬戶。為每種賬戶提供一個菜單操作界面,要有存款、取款、借、貸等操作。另外還要提供一個取消操作選項。用戶退出這個程序時相關(guān)數(shù)據(jù)應(yīng)該保存到文件里取(出于備份的目的,程序執(zhí)行過程中也要備份)。答案:太難了,不會。9-11.Web 站點地址.a) 編寫一個 URL 書簽管理程序. 使用基于文本的菜單, 用戶可以添加, 修改或者刪除書簽數(shù)據(jù)項. 書簽數(shù)據(jù)項中包含站點的名稱, URL 地址, 以及一行簡單說明(可選). 另外提供檢索功能,可以根據(jù)檢索關(guān)鍵字在站點名稱和 URL 兩部

14、分查找可能的匹配. 程序退出時把數(shù)據(jù)保存到一個磁盤文件中去; 再次執(zhí)行時候加載保存的數(shù)據(jù).b)改進 a) 的解決方案, 把書簽輸出到一個合法且語法正確的 HTML 文件(.html 或 htm )中,這樣用戶就可以使用瀏覽器查看自己的書簽清單. 另外提供創(chuàng)建文件夾功能, 對相關(guān)的書簽進行分組管理.附加題: 請閱讀 Python 的 re 模塊了解有關(guān)正則表達式的資料, 使用正則表達式對用戶輸入的 URL 進行驗證.答案:不會做,參考自import re,osdef checkurl(url):regex = pile(r(?:http|ftp)?:/ #http:/ or https:/r(?

15、:(?:A-Z0-9(?:A-Z0-90,61A-Z0-9)?.)+(?:A-Z2,6.?|A-Z0-9-2,.?)|rlocalhost #localhostrd1,3.d1,3.d1,3.d1,3)r(?:d+)?r(?:/?|/?S+)$, re.IGNORECASE)if regex.match(url):return Trueelse:return Falsedef geturl():name = raw_input(pls input a url name: )while 1:url = raw_input(pls input a url address: )if checkurl

16、(url):breakelse:print wrong url format, pls input againmark = raw_input(pls input a url mark: )folder = raw_input(pls input a url folder: )return (name,url,mark,folder)def load(filename):f = open(filename,a+)bmlist = f.readlines()f.close()return bmlistdef save(bmlist,filename):f = open(filename,w+)f

17、or line in bmlist:if len(line):continuef.write(line)f.close()def add(bmlist,name,url,mark,folder = default):bookmark = bookmark = name + ; + url + ; + mark + ; + folder + os.linesepif bookmark not in bmlist:bmlist.append(bookmark)def modify(bmlist,index,name,url,mark,folder):bookmark = bookmark = na

18、me + ; + url + ; + mark + ; + folder + os.linesepbmlistindex = bkdef delbm(bmlist,index):bmlist.pop(index)def findbk(bmlist,fname,furl):for i,item in enumerate(bmlist):(name,url,mark,folder) = item.split(;)if fname and furl:if (fname in name) and (furl in url):return iif fname and (fname in name):re

19、turn iif furl and (furl in url):return ielse:return -1def output2html(bmlist):for i,item in enumerate(bmlist):(name,url,mark,folder) = item.split(;)os.mkdir(folder.strip()filename = name.strip() + .htmlf = open(filename,w+)fmt = %dt%st%st%st%sf.write(bookmark)content = fmt % (i+1,name,rhttp: + url,u

20、rl,mark,folder)f.write(content)f.write()f.close()os.rename(filename,folder.strip()+os.sep+filename)bmlist = load(url.txt)print bmlistwhile True:print 0. quitprint 1. add a url bookmarkprint 2. modify a url bookmarkprint 3. delete a url bookmarkprint 4. find a url bookmarkprint 5. output url bookmark

21、 as htmlprint niInput = input(please input operation num: )if(0 = iInput):save(bmlist,rurl.txt)breakelif (iInput5):print Error input operation,try again. 0 operation is quitncontinueelif 1 = iInput:data = geturl()add(bmlist,*data)print bmlistelif 2 = iInput:index = int(raw_input(bookmark index: )dat

22、a = geturl()modify(bmlist,index,*data)print bmlistelif 3 = iInput:index = int(raw_input(bookmark index: )delbm(bmlist,index)print bmlistelif 4 = iInput:name = raw_input(url name: )url = raw_input(url address: )index = findbk(bmlist,name,url)if index = -1:print not foundelse:print bmlistindexelif 5 =

23、 iInput:output2html(bmlist)9-12 用戶名和密碼?;仡櫨毩?-5,修改代碼使之可以支持“上次登錄時間”。請參閱time模塊中的文檔了解如何記錄用戶上次登錄的時間。另外提供一個系統(tǒng)管理員,他可以導(dǎo)出所有用戶的用戶名,密碼(如需要可以加密),以及上次登錄時間。a)數(shù)據(jù)應(yīng)保存在磁盤中,使用冒號:分隔,一次寫入一行,例如“Joe:boohoo:953176591.145,文件中數(shù)據(jù)的行數(shù)應(yīng)該等于你系統(tǒng)上的用戶數(shù)。b)進一步改進你的程序,不再一次寫入一行,而使用pickle模塊保存整個數(shù)據(jù)對象。請參閱pickle模塊的文檔了解如何序列化/扁平化對象,以及如何讀寫保存的對象。一

24、般來說,這個解決方案的代碼行數(shù)要比a)少;c)使用shelve模塊替換pickle模塊,由于可以省去一些維護代碼,這個解決方案的代碼比b)的更少。答案:from datetime import datetimeimport hashlib,osimport pickle as pimport shelve as sdb = def newuser():value = prompt = login name desired again: while True:name = raw_input(prompt).lower()if not name.isalnum() and in name:pri

25、nt name format errorcontinueelse:if db.has_key(name):prompt = name taken,try another: continueelse:breakpwd = raw_input(login passwd desired: )m = hashlib.md5()m.update(pwd)value.append(m.hexdigest()value.append(datetime.now()dbname = valueprint new user is %s, register time is %s %(name,dbname1)def

26、 olduser():name = raw_input(login name desired again: ).lower()pwd = raw_input(login passwd desired: )m = hashlib.md5()m.update(pwd)passwd = db.get(name)if passwd0 = m.hexdigest():newtime = datetime.now()if (newtime - dbname1).days = 0 and (newtime - dbname1).seconds 14400:print you already logged i

27、n at %s: %(dbname1)else:passwd1 = newtimeprint welcome back %s, login time is %s %(name,passwd1)else:print login incorrectdef removeuser():print dbname = raw_input(input a user name to remove: ).lower()if name in db:db.pop(name)else:print input errordef userlogin():while True:name = raw_input(login

28、name desired: ).lower()if not name.isalnum() and in name:print name format errorcontinueelse:if not db.has_key(name):print user name is not in dbanswer = raw_input(register a new user? y/n).lower()if y = answer:newuser()breakelif n = answer:breakelse:print user name is already in dbolduser()breakdef

29、 outputA():print dbf = open(account.txt,w)for key in db:user = key + : + dbkey0 + : + str(dbkey1) + os.linesepf.write(user)f.close()def outputB():accountfile = pickle.dataf = open(accountfile,w)p.dump(db,f)f.close()f = open(accountfile)accountdb = p.load(f)print accountdbdef outputC():accountfile =

30、shelve.dataaccountdb = s.open(accountfile,c)accountdbdata = dbaccount.close()accountdb = s.open(accountfile,r)print accountdbdatadef adminlogin():while True:name = raw_input(login name desired: ).lower()if not name.isalnum() and in name:print name format errorcontinueelse:pwd = raw_input(login passw

31、d desired: )if name = root and pwd = root:print welcome adminbreakelse:print user name or passwd is wrong,input againif len(db) = 0:print there is nothing you can doelse:answer = raw_input(output all account? y/n).lower()if y = answer:outputC()elif n = answer:print byedef showmenu():prompt = (A)dmin

32、 login(U)ser login(R)emove a existing user(Q)uitEnter choice: done = Falsewhile not done:chosen = Falsewhile not chosen:try:choice = raw_input(prompt).strip()0.lower()except (EOFError,keyboardInterrupt):choice = qprint nYou picked: %s % choiceif choice not in aurq:print invalid option.try againelse:

33、chosen = Trueif choice = q:done = Trueif choice = r:removeuser()if choice = u:userlogin()if choice = a:adminlogin()if _name_ = _main_:showmenu()913. 命令行參數(shù)a) 什么是命令行參數(shù), 它們有什么用?b) 寫一個程序, 打印出所有的命令行參數(shù)。答案:a)命令行參數(shù)是調(diào)用某個程序時除程序名以外的其他參數(shù)。命令行參數(shù)使程序員在啟動一個程序時對程序行為作出選擇。b)import sysprint str(sys.argv)9-14 記錄結(jié)果。修改你的計算

34、器程序(練習5-6)使之接受命令行參數(shù)。例如$ calc.py 1 + 2 只輸出計算結(jié)果。另外,把每個表達式和它的結(jié)果寫入到一個磁盤文件中,當使用下面的命令時 $ calc.py print 會把記錄的內(nèi)容顯示到屏幕上,然后重置文件。這里是樣例展示:$ calc.py 1 + 23$ calc.py 3 327$ calc.py print1 + 233 327$ calc.py print$ 答案:#coding:utf-8import sys,osdef calculator(expression):operator = +,-,*,/,%,*sysmol = for i in oper

35、ator:if i in sys.argv:sysmol = iif sysmol = :print 操作符錯誤returnnum = expression.split(sysmol)if . in num0 or . in num1:num1 = float(num0)num2 = float(num1)else:num1 = int(num0)num2 = int(num1)f = open(test.txt,a+)f.write(expression)if sysmol = operator0:result = str(num1 + num2) + os.linesepprint res

36、ult,f.write(result)elif sysmol = operator1:result = str(num1 - num2) + os.linesepprint result,f.write(result)elif sysmol = operator2:result = str(num1 * num2) + os.linesepprint result,f.write(result)elif sysmol = operator3:result = str(num1 / num2) + os.linesepprint result,f.write(result)elif sysmol

37、 = operator4:result = str(num1 % num2) + os.linesepprint result,f.write(result)elif sysmol = operator5:result = str(num1 * num2) + os.linesepprint result,f.write(result)if sys.argv1 = print:if os.path.exists(rtest.txt):f = open(test.txt,r)for line in f:print line,f.close()else:print file not exist.e

38、lse:expression = str(sys.argv1 + + sys.argv2 + + sys.argv3+ os.linesep)calculator(expression)915. 復(fù)制文件. 提示輸入兩個文件名(或者使用命令行參數(shù)). 把第一個文件的內(nèi)容復(fù)制到第二個文件中去.答案:import sysfile1 = sys.argv1file2 = sys.argv2f1 = open(file1,r)f2 = open(file2,a+)f2.write(n)for line in f1:f2.write(line)f1.close()f2.close()916. 文本處理。

39、人們輸入的文字常常超過屏幕的最大寬度。編寫一個程序, 在一個文本文件中查找長度大于 80 個字符的文本行。從最接近 80 個字符的單詞斷行,把剩余文件插入到下一行處.程序執(zhí)行完畢后,應(yīng)該沒有超過 80 個字符的文本行了。答案:這個基本能達到要求,不過最后一行會少個字符或結(jié)尾符號,因為最后一行沒有換行符file = open(test1.txt,r)list1 = for line in file:symbol = Truewhile symbol:if len(line) = 80:list1.append(line:-1)symbol = Falseelse:count = len(line

40、)/80for i in range(count):list1.append(line:81)line = line81:print list1file1 = open(test2.txt,a+)for i in list1:file1.write(i)file1.write(n)方法二:file = open(test1.txt,r)list1 = for line in file:symbol = Truewhile symbol:if len(line) = 80:list1.append(line)symbol = Falseelse:list1.append(line:81)line

41、 = line81:print list1file1 = open(test2.txt,a+)for i in list1:if i.endswith(n):i = i:-1file1.write(i)file1.write(n)917. 文本處理。創(chuàng)建一個原始的文本文件編輯器。你的程序應(yīng)該是菜單驅(qū)動的,有如下這些選項:1) 創(chuàng)建文件(提示輸入文件名和任意行的文本輸入);2) 顯示文件(把文件的內(nèi)容顯示到屏幕);3) 編輯文件(提示輸入要修改的行, 然后讓用戶進行修改);4) 保存文件;5) 退出.答案:這里把3編輯文件和4保存文件合并在一起了import osdef newfile():sy

42、mbol = Truewhile symbol:filename = raw_input(Enter a filename: )if os.path.exists(filename):print file is exists.else:symbol1 = Truewhile symbol1:content = raw_input(Enter content(q for quit): )if content = q:breakf1 = open(filename,a+)f1.write(content)f1.write(n)f1.close()symbol = Falsedef showfile

43、():symbol = Truewhile symbol:filename = raw_input(Enter a filename: )if not os.path.exists(filename):print file is not exists.else:f1 = open(filename,r)for line in f1:print line,f1.close()breakdef editfile():symbol = Truewhile symbol:filename = raw_input(Enter a filename: )if not os.path.exists(file

44、name):print file is not exists.else:index = int(raw_input(edit index of line: )con = raw_input(Enter edit content: )ls = f = open(filename,r)ls = f.readlines()f.close()lsindex - 1 = con + os.linesepf1 = open(filename,w)for line in ls:f1.write(line)f1.close()symbol = Falsedef showmenu():prompt = Menu

45、:(N)ewfile(S)howfile(E)ditfile(Q)uitEnter choice: done = Truewhile done:chosen = Truewhile chosen:try:choice = raw_input(prompt).strip()0.lower()except (EOFError,KeyboardInterrupt):choice = qprint nYou picked: %s % choiceif choice not in ncesq:print invalid option, try againelse:chosen = Falseif cho

46、ice = q:breakif choice = n:newfile()if choice = s:showfile()if choice = e:editfile()if _name_ = _main_:showmenu()918. 搜索文件. 提示輸入一個字節(jié)值(0 - 255)和一個文件名. 顯示該字符在文件中出現(xiàn)的次數(shù)。答案:num = int(raw_input(Enter a number between 0 255: )filename = raw_input(Enter filename: )ch = chr(num)numcount = 0f = open(filename,

47、r)for line in f:numcount += line.count(ch)print numcount919. 創(chuàng)建文件。創(chuàng)建前一個問題的輔助程序。創(chuàng)建一個隨機字節(jié)的二進制數(shù)據(jù)文件,但某一特定字節(jié)會在文件中出現(xiàn)指定的次數(shù)。該程序接受三個參數(shù):1) 一個字節(jié)值( 0 - 255 );2) 該字符在數(shù)據(jù)文件中出現(xiàn)的次數(shù);3) 數(shù)據(jù)文件的總字節(jié)長度。你的工作就是生成這個文件,把給定的字節(jié)隨機散布在文件里,并且要求保證給定字符在文件中只出現(xiàn)指定的次數(shù),文件應(yīng)精確地達到要求的長度。答案:import randomdef abc(num, count, len):l = n = len - co

48、untfor i in range(n):randomnum = random.randint(0,255)symbol = Truewhile symbol:if randomnum = num:randomnum = random.randint(0,255)else:l.append(randomnum)symbol = Falsefor i in range(count):l.append(num)random.shuffle(l)print lf = open(test.txt,w)f.close()for i in l:f = open(test.txt,a+)f.write(%08d %d % (int(bin(i)2:),i)f.write(n)f.close()print %08d %d % (int(bin(i)2:),i)abc(66,5,20)920.壓縮文件。寫一小段代碼,壓縮/解壓縮gzip或bzip格式的文件。可以使用命令行下的gzip或bzip2以及GUI程序PowerArchiver,StuffIt,或WinZip來確認你的Pyt

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論