chapter 9 exercise

9–1. 文件过滤. 显示一个文件的全部行, 忽略以井号( # )开头的行. 这个字符被用作 Python , Perl, Tcl, 等大多脚本文件的注释符号. 附加题: 处理不是第一个字符开头的注释. import os filename=raw_input('please input you file name:') fobj=open(filename,'r') data=[line.strip() for line in fobj.readlines()] fobj.close() print data for string in data:     if string[0]!='#':        print string 9–2. 文件访问. 提示输入数字 N 和文件 F, 而后显示文件 F 的前 N 行. code: import os File=raw_input('please input filename:') Num=int(raw_input('please input the number:')) fobj=open(File,'r') Line=[line.strip() for line in fobj.readlines()] for i in range(Num):     print Line[i] fobj.close() 9–3. 文件信息. 提示输入一个文件名, 而后显示这个文本文件的总行数. import os File=raw_input('please input filename:') fobj=open(File) i=0 for line in fobj:     i=i+1 print i fobj.close() another code: import os File=raw_input('please input filename:') fobj=open(File) length=len([line for line in fobj]) print length fobj.close() question:length=len([line for line infobj])为何只能用列表解析却不能用生成器表达式(length=len(line for line infobj))解析呢? 9–4. 文件访问. 写一个逐页显示文本文件的程序. 提示输入一个文件名, 每次显示文本 文件的 25 行, 暂停并向用户提示"按任意键继续.", 按键后继续执行. tips: 让Python脚本暂停执行的几种方法求解, 2. raw_input( ) 经过等待输入来让程序暂停 3. os.system("pause") 经过执行操做系统的命令来让程序暂停,该函数是经过实现标准C函数system( )来实现的。 code: import os def showTextPage(filename):     f=open(filename)     n=0     for eachline in f:        print eachline        n=n+1        if n%==0:                      os.system('pause')           continue     f.close() filename=raw_input('please input filename:') showTextPage(filename) 9–5. kaoshi成绩. 改进你的kaoshi成绩问题(练习 5 -3 和 6-4), 要求能从多个文件中读入kaoshi成绩. 文件的数据格式由你本身决定. 难点:多个文件中读取。 code: 5-3 标准类型运算符. 写一段脚本,输入一个测验成绩,根据下面的标准,输出他的评分 成绩(A-F)。 A: 90–100 B: 80–89 C: 70–79 D: 60–69 F: <60 术. 更新上一章里面你的得分测试练习方案,把测试得分放到一个列表中去.你的代 码应该能够计算出一个平均分 9–6. 文件比较. 写一个比较两个文本文件的程序. 若是不一样, 给出第一个不一样处的行号和 列号. filename1=raw_input('please input file1;') filename2=raw_input('please input file2:') fobj1=open(filename1) fobj2=open(filename2) def compareline(line1,line2):     t=len(lene1) iflen(line1)     for j in range(t):        if line1[j]!=line2[j]:            print'j islist%d' %(j+1)           break def textCompare(fobj1,fobj2):    line1=fobj1.readlines()    line2=fobj2.readlines()     for i inrange(len(line1)):        if line1[i]!=line2[i]:            print 'iis row%d'%(i+1)           compareline(line1[i],line2[i])           break     else:        print 'exactly the same.' textCompare(fobj1,fobj2) fobj1.close() fobj2.close() 9–7. 解析文件. Win32 用户: 建立一个用来解析 Windows .ini 文件的程序. POSIX用户: 建立一个解析 /etc/serves 文件的程序. 其它平台用户: 写一个解析特定结构的系统配置文件的 程序. code: def parseIni(filename):     f=open(filename)     dict1={}     for eachLine in f:        index=eachLine.find('=')        if index!=-1:           key=eachLine[:index].strip()           value=eachLine[index+1:].strip()           dict1[key]=value     for key in dict1:        print key,'=',dict1[key]     f.close() parseIni('system.ini') 9–8. 模块研究. 提取模块的属性资料. 提示用户输入一个模块名(或者从命令行接受输入). 而后使用 dir() 和其它内建函数提取模块的属性, 显示它们的名字, 类型, 值. code: 暂时还没搞懂 import os module=raw_input('please input the module name:') def getattribute(module):     a=help(module)    f=open('module.txt','w')    f.write('%s%s'%(a,os.linesep))     f.close() getattribute(module) 9–9. Python 文档字符串. 进入 Python 标准库所在的目录. 检查每一个 .py 文件看是否有 __doc__ 字符串, 若是有, 对其格式进行适当的整理归类. 你的程序执行完毕后, 应该会生成一个 漂亮的清单. 里边列出哪些模块有文档字符串, 以及文档字符串的内容. 清单最后附上那些没有文 档字符串模块的名字. 附加题: 提取标准库中各模块内所有类(class)和函数的文档. import os import sys path=r'C:\Python27\Lib\aifc.py' fileobj1=open('docstring.txt','a+') fobj=open(path) strTemp='' hasDoc=False for eachline in fobj:     if (not hasDoc) andeachline.startswith('"""'):        hasDoc = True     elif hasDoc andeachline.startswith('"""'):        hasDoc = False        strTemp += eachline        break     if hasDoc:        strTemp += eachline     else:        break if strTemp != "":         fileobj1.write("filename:"+os.linesep)         fileobj1.write("__doc__ is:" +os.linesep)         fileobj1.write(strTemp +os.linesep) strTemp = "" fobj.close() fileobj1.close() 9–13. 命令行参数 a) 什么是命令行参数, 它们有什么用? b) 写一个程序, 打印出全部的命令行参数. 命令行参数是指经过命令行传入的参数。sys.argv,当你在文本环境下编写代码须要在cmd下运行时必须经过命令行参数向程序传输参数。 命令行参数是调用某个程序时除程 序名之外的其它参数 import sys for i in range(1,len(sys.argv)):     printi,sys.argv[i] 经过cmd执行该程序并输入参数。 9–14. 记录结果. 修改你的计算器程序(练习 5-6 )使之接受命令行参数. 例如: $ calc.py 1 + 2 只输出计算结果. 另外, 把每一个表达式和它的结果写入到一个磁盘文件中. 当使用下面的命令 时: $ calc.py print Edit By Vheavens Edit By Vheavens 会把记录的内容显示到屏幕上, 而后重置文件. 这里是样例展现: import os import sys def count(express):     for a in express:        i=express.index(a)        if a=='+':            returnint(express[:i])+ int(express[i+1:])        elif  a=='-':            returnint(express[:i])- int(express[i+1:])        elif a=='*':            returnint(express[:i])* int(express[i+1:])        elif a=='/'and int(express[i+1:])!=0:            returnint(express[:i])/ int(express[i+1:])        elif a=='%'and int(express[i+1:])!=0:            returnint(express[:i])% int(express[i+1:])        elif a=='**'and int(express[i+1:])!=0:            returnint(express[:i])** int(express[i+1:])     else:        return 'invalue express,please inputagain' if __name__=='__main__':    express=sys.argv[1]     if express=='print':        with open('result.txt') as fobj:            printfobj.read()        os.remove('result.txt')     else:        with open('result.txt','a+') as fobj:           fobj.write(sys.argv[1])           fobj.write('='+str(count(sys.argv[1])))           fobj.write('\n')     print 'the resultis:%d'%(count(sys.argv[1])) 9–15. 复制文件. 提示输入两个文件名(或者使用命令行参数). 把第一个文件的内容复制 到第二个文件中去. code: import sys import os file1=raw_input('please input filename:') file2=raw_input('please input filename2:') fobj1=open(file1) fobj2=open(file2,'w') for eachline in fobj1:    fobj2.write(eachline+os.linesep) fobj1.close() fobj2.close() code2:用sys.argv传递参数 import sys import os #file1=raw_input('please input filename:') #file2=raw_input('please input filename2:') fobj1=open(sys.argv[1]) fobj2=open(sys.argv[2],'w') for eachline in fobj1:    fobj2.write(eachline+os.linesep) fobj1.close() fobj2.close() 9–16. 文本处理. 人们输入的文字经常超过屏幕的最大宽度. 编写一个程序, 在一个文本 文件中查找长度大于 80 个字符的文本行. 从最接近 80 个字符的单词断行, 把剩余文件插入到 下一行处. 程序执行完毕后, 应该没有超过 80 个字符的文本行了. code: import sys import os with open('newfile.txt') as fobj:     withopen('temp.txt','w')as fobj2:        for eachline in fobj:            iflen(eachline)>80:              eachline1=list(eachline)               num=len(eachline1)/80               for i in range(num):                  fobj2.write(''.join(eachline[:79]))                  fobj2.write(os.linesep)                  eachline=eachline[79:]              fobj2.write(''.join(eachline))           else:              fobj2.write(eachline+os.linesep)     fobj2.close()     fobj.close() 这个代码有个问题就是有的时候那个一行末尾的单词会被截断,再kaolv一个。kaolv到这个我忽然想到在第八章里面有个表达式解析好像有这个方法, 去回顾一下去。 附加题: 须要计算出全部非空白字符的数目。 And the Lord spake, saying, "First shalt thou take out the Holy Pin. Then shalt thou count to three, Edit By Vheavens Edit By Vheavens no more, no less. Three shall be the number thou shalt count, and the number of the counting shall be three. Four shalt thou not count, nei- ther count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thy foe, who, being naughty in My sight, shall snuff it." code: f = open('hhga.txt', 'r') sum=len([word for line in f for word in line.split()]) 9–17. 文本处理. 建立一个原始的文本文件编辑器. 你的程序应该是菜单驱动的, 有以下 这些选项: 1) 建立文件(提示输入文件名和任意行的文本输入), 2) 显示文件(把文件的内容显示到屏幕), 3) 编辑文件(提示输入要修改的行, 而后让用户进行修改), 4) 保存文件, 以及 5) 退出. code: 9–18. 搜索文件. 提示输入一个字节值(0 - 255)和一个文件名. 显示该字符在文件中出现 的次数. code: chr=raw_input('please input character:') filename=raw_input('please input filename:') fobj=open(filename) j=0 for eachline in fobj:    list1=list(eachline)     for i inrange(len(list1)):        if chr==list1[i]:           j=j+1 fobj.close() print j 或者使用字符串计数函数;string.count(chr) chr=raw_input('please input character:') filename=raw_input('please input filename:') fobj=open(filename) j=0 for eachline in fobj:    j=j+eachline.count(chr) fobj.close() print j 9–19. 建立文件. 建立前一个问题的辅助程序. 建立一个随机字节的二进制数据文件, 但 某一特定字节会在文件中出现指定的次数. 该程序接受三个参数: 1) 一个字节值( 0 - 255 ), 2) 该字符在数据文件中出现的次数, 以及 3) 数据文件的总字节长度. 你的工做就是生成这个文件, 把给定的字节随机散布在文件里, 而且要求保证给定字符在文件 中只出现指定的次数, 文件应精确地达到要求的长度. code: import os import random def fun(chr,countNum,length):     num=[]     firstlength=length     whilefirstlength-countNum:        char=random.choice(xrange(255))        num.append(char)        firstlength=firstlength-1     for i inrange(countNum):        num.append(chr)    random.shuffle(num)     return num if __name__=='__main__':     while True:        chr=int(raw_input('please input the charter youwant to(0 to quit) :'))        countNum=int(raw_input('please input thetimes:'))        length=int(raw_input('please input the totalltimes'))        if chr==0:           break        elif length            print'wrong ,please input again'           break        else:           num=fun(chr,countNum,length)            for i innum:               print '{0:b}'.format(i) 9–20. 压缩文件. 写一小段代码, 压缩/解压缩 gzip 或 bzip 格式的文件. 可使用命令 行下的 gzip 或 bzip2 以及 GUI 程序 PowerArchiver , StuffIt , 或 WinZip来确认你的 Python 支持这两个库. code: import zipfile with zipfile.ZipFile('hello.zip','w')as myzip:    myzip.write('text.txt') ////////////////////////////////////// import zipfile f=zipfile.ZipFile('text.zip','w') f.write('text.txt') f.write('temp.txt') f.close() /////////////////////////////// 9–21. ZIP 归档文件. 建立一个程序, 能够往 ZIP 归档文件加入文件, 或从中提取文件, 有可能的话, 加入建立ZIP 归档文件的功能.
相关文章
相关标签/搜索