python核心编程第二版课后题答案第九章.docx
- 文档编号:24004318
- 上传时间:2023-05-23
- 格式:DOCX
- 页数:16
- 大小:26.77KB
python核心编程第二版课后题答案第九章.docx
《python核心编程第二版课后题答案第九章.docx》由会员分享,可在线阅读,更多相关《python核心编程第二版课后题答案第九章.docx(16页珍藏版)》请在冰豆网上搜索。
python核心编程第二版课后题答案第九章
9.11练习
9–1.文件过滤.显示一个文件的所有行,忽略以井号(#)开头的行.这个字符被用做Python,Perl,Tcl,等大多脚本文件的注释符号.
附加题:
处理不是第一个字符开头的注释.
withopen("data.txt")asfobj:
foreachlineinfobj:
ifnoteachline.startswith("#"):
printeachline
附件题看不懂。
。
。
。
。
9–2.文件访问.提示输入数字N和文件F,然后显示文件F的前N行.
filename=raw_input("pleaseenterthefilename:
")
num=int(raw_input("pleaseenterthelinenumber:
"))
foreachlineinopen(filename):
ifnum:
printeachline
num-=1
else:
break
程序输出:
>>>
pleaseenterthefilename:
data.txt
pleaseenterthelinenumber:
5
#第一行
helloworld
#第二行
ilovethisworld
#第三行
9–3.文件信息.提示输入一个文件名,然后显示这个文本文件的总行数.
filename=raw_input("pleaseenterthefilename:
")
printlen([lineforlineinopen(filename)])
程序输出:
>>>
pleaseenterthefilename:
data.txt
8
9–4.文件访问.写一个逐页显示文本文件的程序.提示输入一个文件名,每次显示文本文件的25行,暂停并向用户提示"按任意键继续.",按键后继续执行.
withopen("data.txt","a+")asfobj:
foriinrange(100):
fobj.write(str(i))
fobj.write("\n")
withopen("data.txt")asfobj:
num=1
foreachlineinfobj:
ifnum%26!
=0:
printeachline,
num+=1
else:
go=raw_input("continue(ctocontinue,othertoquit):
")
num+=1
ifgo!
="c":
break
9–6.文件比较.写一个比较两个文本文件的程序.如果不同,给出第一个不同处的行号和列号.
fobj1=open("data1.txt")
fobj2=open("data2.txt")
lines1=fobj1.readlines()
lines2=fobj2.readlines()
foriinrange(min(len(lines1),len(lines2))):
iflines1[i]!
=lines2[i]:
printi
break
9–7.解析文件.Win32用户:
创建一个用来解析Windows.ini文件的程序.
这道题我没看懂,如何解析?
?
?
9–9.Python文档字符串.进入Python标准库所在的目录.检查每个.py文件看是否有__doc__字符串,如果有,对其格式进行适当的整理归类.你的程序执行完毕后,应该会生成一个漂亮的清单.里边列出哪些模块有文档字符串,以及文档字符串的内容.清单最后附上那些没有文档字符串模块的名字.
附加题:
提取标准库中各模块内全部类(class)和函数的文档.
这道题忽悠了我一个晚上。
第一:
根本就不存在__doc__的字符串,当我们运行模块.__doc__的时候,实际上是读取开头的字符串。
所以我们要判断是开头是否存在“”“字符串”“”这样的格式。
程序如下:
importos
importsys
num=[]
"""将所有路径文件名全部提出出来"""
deffun(dirName):
foriinos.listdir(dirName):
ifos.path.isdir(dirName+"\\"+i):
fun(dirName+"\\"+i)
else:
num.append(dirName+"\\"+i)
fun(r"C:
\Python27\Lib")
hasDoc=False
strTemp=""
fileobj1=open("hasdoc.txt","a+")
fileobj2=open("nodoc.txt","a+")
foriinnum:
fobj=open(i)
foreachlineinfobj:
if(nothasDoc)andeachline.startswith('"""'):
hasDoc=True
elifhasDocandeachline.startswith('"""'):
hasDoc=False
strTemp+=eachline
break
ifhasDoc:
strTemp+=eachline
else:
break
ifstrTemp!
="":
fileobj1.write("文件名:
"+i+"\n")
fileobj1.write("__doc__is:
"+"\n")
fileobj1.write(strTemp+"\n")
else:
fileobj2.write("文件名:
"+i+"\n")
strTemp=""
fobj.close()
fileobj1.close()
fileobj2.close()
今天头好疼!
!
真的好疼,一点看书的欲望都没有。
最近还花了点时间学习wxpython,专门用来对付习题9-10,9-11这种图形界面的设计,但是发现学习的蛋疼,可能我这人不太喜欢用UI这些东西吧。
所以,习题9-10,9-11,9-12就不做了。
9–13.命令行参数
a)什么是命令行参数,它们有什么用?
b)写一个程序,打印出所有的命令行参数.
a)跟随着命令写入的参数,主要用于linux下运行程序
#coding=utf-8
importsys
foriinrange(1,len(sys.argv)):
print"parameter%d:
%s"%(i,sys.argv[i])
程序输入输出:
习题9-14
#coding=utf-8
"""计算器程序,模仿内建函数eval()"""
importsys
importos
defnew_eval(num):
ifnum[1]=="+":
returnint(num[0])+int(num[2])
elifnum[1]=="-":
returnint(num[0])-int(num[2])
elifnum[1]=="*":
returnint(num[0])*int(num[2])
elifnum[1]=="/":
returnint(num[0])/int(num[2])
elifnum[1]=="%":
returnint(num[0])%int(num[2])
elifnum[1]=="**":
returnint(num[0])**int(num[2])
else:
return"erroroperator"
if__name__=="__main__":
ifsys.argv[1:
][0]=="print":
withopen("result.txt")asfobj:
printfobj.read()
os.remove("result.txt")
else:
withopen("result.txt","a+")asfobj:
fobj.write("".join(sys.argv[1:
]))
fobj.write("\n")
fobj.write(str(new_eval(sys.argv[1:
])))
fobj.write("\n")
print"theresultis:
%d"%(new_eval(sys.argv[1:
]))
不要小看任何一个小程序,这段代码我写了很久,很多细节的东西都没有掌握,也可能是太久没写python代码的缘故吧。
程序输入输出:
9–15.复制文件.提示输入两个文件名(或者使用命令行参数).把第一个文件的内容复制到第二个文件中去.
#coding=utf-8
file1=raw_input("pleaseenterfile1:
")
file2=raw_input("pleaseenterfile2:
")
withopen(file1)asfobj1:
withopen(file2,"w")asfobj2:
foriinfobj1:
fobj2.write(i)
withopen(file2)asfobj2:
printfobj2.read()
程序输入输出:
>>>
pleaseenterfile1:
hello.txt
pleaseenterfile2:
world.txt
helloworld
无论如何,都要坚持下去
加油
9–16.文本处理.人们输入的文字常常超过屏幕的最大宽度.编写一个程序,在一个文本文件中查找长度大于80个字符的文本行.从最接近80个字符的单词断行,把剩余文件插入到下一行处.程序执行完毕后,应该没有超过80个字符的文本行了.
importos
file1=raw_input("pleaseenterthefile:
")
withopen(file1)asfobj1:
withopen("temp.txt","w")asfobj2:
foriinfobj1:
iflen(i)>80:
num=list(i)
count=len(num)/80
foriinrange(count):
fobj2.write("".join(num[:
79]))
fobj2.write("\n")
num=num[79:
]
fobj2.write("".join(num))
else:
fobj2.write(i)
fobj2.write("\n")
withopen("temp.txt")asfobj2:
withopen(file1,"w")asfobj1:
foriinfobj2:
fobj1.write(i)
os.remove("temp.txt")
9–17.文本处理.创建一个原始的文本文件编辑器.你的程序应该是菜单驱动的,有如下
这些选项:
1)创建文件(提示输入文件名和任意行的文本输入),
2)显示文件(把文件的内容显示到屏幕),
3)编辑文件(提示输入要修改的行,然后让用户进行修改),
4)保存文件,以及
5)退出.
classfileEdit(object):
defnewFile(self,fileName,fileText):
withopen(fileName,"a+")asfobj:
fobj.write(fileText)
defshowFile(self,fileName):
strTemp=""
withopen(fileName)asfobj:
foriinfobj:
strTemp+=i
returnstrTemp
defeditFile(self,fileName,lineNum,newText):
lines=[]
withopen(fileName)asfobj:
lines=fobj.readlines()
iflineNum>len(lines):
returnFalse
lines[lineNum-1]=newText
withopen(fileName,"w")asfobj:
fobj.writelines(lines)
if__name__=="__main__":
whileTrue:
fobj=fileEdit()
print"ntonewfile"
print"stoshowfile"
print"etoeditfile"
print"andqtoquitfile"
choice=raw_input("pleaseenterthechoice:
")
ifchoice.lower()=="q":
break
ifchoice.lower()notin["n","s","e"]:
continue
else:
ifchoice.lower()=="n":
fileName=raw_input("pleaseenterthefilename:
")
fileText=""
whileTrue:
Text=raw_input("pleaseenterthetext(qtoquit):
")
ifText.lower()=="q":
break
fileText+=Text
fileText+="\n"
fobj.newFile(fileName,fileText)
elifchoice.lower()=="s":
fileName=raw_input("pleaseenterthefilename:
")
printfobj.showFile(fileName)
elifchoice.lower()=="e":
fileName=raw_input("pleaseenterthefilename:
")
lineNum=int(raw_input("pleaseenterthelineNumber:
"))
lineText=raw_input("pleaseenterthenewText:
")
fobj.editFile(fileName,lineNum,lineText)
程序输入输出:
>>>
ntonewfile
stoshowfile
etoeditfile
andqtoquitfile
pleaseenterthechoice:
n
pleaseenterthefilename:
hello.txt
pleaseenterthetext(qtoquit):
helloworld
pleaseenterthetext(qtoquit):
ilovethisworld
pleaseenterthetext(qtoquit):
andilovepythontoo
pleaseenterthetext(qtoquit):
q
ntonewfile
stoshowfile
etoeditfile
andqtoquitfile
pleaseenterthechoice:
e
pleaseenterthefilename:
hello.txt
pleaseenterthelineNumber:
3
pleaseenterthenewText:
iloveyou
ntonewfile
stoshowfile
etoeditfile
andqtoquitfile
pleaseenterthechoice:
s
pleaseenterthefilename:
hello.txt
helloworld
ilovethisworld
iloveyou
ntonewfile
stoshowfile
etoeditfile
andqtoquitfile
pleaseenterthechoice:
q
9–18.搜索文件.提示输入一个字节值(0-255)和一个文件名.显示该字符在文件中出现的次数.
fileName=raw_input("pleaseenterthefileName:
")
fileCh=raw_input("pleaseenterthecharacter:
")
countNum=0
withopen(fileName)asfobj:
foriinfobj:
countNum+=i.count(fileCh)
print"character%soccurs:
%d"%(fileCh,countNum)
程序输入输出:
>>>
pleaseenterthefileName:
hello.txt
pleaseenterthecharacter:
l
characterloccurs:
6
9–19.创建文件.创建前一个问题的辅助程序.创建一个随机字节的二进制数据文件,但
某一特定字节会在文件中出现指定的次数.该程序接受三个参数:
1)一个字节值(0-255),
2)该字符在数据文件中出现的次数,以及
3)数据文件的总字节长度.
这道题很难。
。
。
想了半天,解决方法倒是有,但是不知道怎么去写。
importos
importrandom
deffun(ch,countNum,length):
firstLength=length
num=[]
whilefirstLength-countNum:
chara=random.choice(xrange(255))
ifch==chara:
continue
else:
num.append(chara)
firstLength-=1
foriinrange(countNum):
num.append(ch)
new_num=[]
whilelength:
i=int(random.random()*length)
new_num.append(num[i])
delnum[i]
length-=1
returnnew_num
if__name__=="__main__":
num=fun(25,10,15)
foriteminnum:
print"{0:
b}".format(item)
程序显示,二进制25将会被现实10次,而且是随机排列的:
>>>
1100011
11001
11001
11001
11001
11001
10111
11101000
100100
11001
11001
10000101
11001
11001
11001
9–20.压缩文件.写一小段代码,压缩/解压缩gzip或bzip格式的文件.可以使用命令行下的gzip或bzip2以及GUI程序PowerArchiver,StuffIt,或WinZip来确认你的Python支持这两个库.
importzipfile
withzipfile.ZipFile("hello.zip","w")asmyzip:
myzip.write("hello.txt")
9–21.ZIP归档文件.创建一个程序,可以往ZIP归档文件加入文件,或从中提取文件,有可能的话,加入创建ZIP归档文件的功能.
这道题,坦白说不会。
从Google上很容易找到答案,然后找到答案后好好研究一遍。
importos
importzipfile
defzipdir(path,zip):
forroot,dirs,filesinos.walk(path):
forfileinfiles:
zip.write(os.path.join(root,file))
if__name__=='__main__':
zip=zipfile.ZipFile('Python.zip','w')
zipdir('C:
\\Python27\\',zip)
zip.close()
整体思想和上面的一致,只是增加了路径的查询罢了。
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- python 核心 编程 第二 课后 答案 第九