《Python核心编程习题》---chapter9

来源:互联网 发布:setup.exe mac 打不开 编辑:程序博客网 时间:2024/05/16 04:45
# -*- coding:utf-8 -*-'''Created on 2017-7-19@author: TanWenjing'''#9-1'''文件过滤. 显示一个文件的所有行, 忽略以井号( # )开头的行. 这个字符被用做Python , Perl, Tcl, 等大多脚本文件的注释符号.'''def main():    f = open('Chapter8.py','r')    for eachline in f:        if eachline.startswith('#'):            pass        else:            print eachlineif __name__ == '__main__':    main()#9-2'''文件访问. 提示输入数字 N 和文件 F, 然后显示文件 F 的前 N .'''def file_print(filename, number):    f = open(filename, 'r')    for i in range(number):        print f.readline()    f.close()def main():    filename = raw_input('Please input the file name:')    number = int(raw_input('How many lines do you want to output:'))    file_print(filename, number)if __name__ == '__main__':    main()#9-3'''文件信息. 提示输入一个文件名, 然后显示这个文本文件的总行数.'''def line_number(filename):    f = open(filename, 'r')    count = len(f.readlines())    return countdef main():    filename = raw_input('Please input the file name:')    count = line_number(filename)    print 'It has %d lines.'%(count)if __name__ == '__main__':    main()#9-4'''文件访问. 写一个逐页显示文本文件的程序. 提示输入一个文件名, 每次显示文本文件的 25 , 暂停并向用户提示"按任意键继续.", 按键后继续执行.'''import osdef pageread(filename):    f = open(filename, 'r')    for i, item in enumerate(f):        if (i+1)%25 == 0:            os.system('pause')            print 'Please press any button to continue'        print itemdef main():    filename = raw_input('Please input the file name:')    pageread(filename)if __name__ == '__main__':    main()
#9-6'''文件比较. 写一个比较两个文本文件的程序. 如果不同, 给出第一个不同处的行号和列号.'''def main():    row = 0    fa = open('a.txt', 'r')    fb = open('b.txt', 'r')    for linea, lineb in zip(fa, fb):        if linea == lineb:            row = row+1            print 'The %d line of the two files is the same.'%row        else:            row = row + 1            col = 0            for worda, wordb in zip(linea, lineb):                col = col +1                if worda != wordb:                    print 'The two letters in line %d, col %d are different'%(row , col)
if __name__ == '__main__':    main()
#9-15'''复制文件. 提示输入两个文件名(或者使用命令行参数). 把第一个文件的内容复制到第二个文件中去.'''def main():    filename1 = raw_input('Please input the file name one :')    filename2 = raw_input('Please input the file name two :')    f1 = open(filename1, 'r')    f2 = open(filename2, 'w')    for eachline in f1:        f2.write(eachline)if __name__ == '__main__':    main()#9-16'''文本处理. 人们输入的文字常常超过屏幕的最大宽度. 编写一个程序, 在一个文本文件中查找长度大于 80 个字符的文本行. 从最接近 80 个字符的单词断行, 把剩余文件插入到下一行处.'''import osdef main():    maxlen = 80    with open('58.log','r') as file1:        with open('temp.txt', 'w') as file2:            for eachline in file1:                if len(eachline) > maxlen:                    line = list(eachline)                    for i in range(len(eachline)/maxlen):                        file2.write(''.join(line[:maxlen]))                        file2.write('\n')                        line = line[maxlen:]                    file2.write(''.join(line))                else:                    file2.write(eachline)            file = open('a.txt', 'w')    with open('temp.txt', 'r') as file2:        with open('58.log', 'w') as file1:            for eachline in file2:                file1.write(eachline)    os.remove('temp.txt')if __name__ == '__main__':    main()#9-17'''9–17. 文本处理. 创建一个原始的文本文件编辑器. 你的程序应该是菜单驱动的, 有如下这些选项:1) 创建文件(提示输入文件名和任意行的文本输入),2) 显示文件(把文件的内容显示到屏幕),3) 编辑文件(提示输入要修改的行, 然后让用户进行修改),4) 保存文件, 以及5) 退出'''from functools import partialdef create_file():    filename = raw_input('Please input the file name:')    sentinel = 'end'    with open(filename, 'w') as file:        for sentence in iter(raw_input,sentinel): #迭代到sentinel终止            file.write(sentence)            file.write('\n')    return filenamedef display_file(filename):    with open(filename,'r') as f:        for eachline in f:            print eachlinedef edit_file(filename):    number = int(raw_input('Please input the line number,you want edit:'))    with open(filename,'r') as f:        eachlines = f.readlines()        print eachlines        eachlines[number-1] =raw_input('Please input the new line:')    with open(filename, 'w') as f:        f.writelines(eachlines)    f.close()def save_file():#不太明白保存模块的作用    passdef main():    print """                (C)reate a file.                (D)isplay the file.                (E)dit the file.                (S)ave the file.                (Q)uit"""    choose = raw_input("Please input your choose:").lower()    while(choose != 'q'):        if choose == 'c':            filename = create_file()        elif choose == 'd':            display_file(filename)        elif choose == 'e':            edit_file(filename)        elif choose == 's':            save_file(filename)        else:            print 'You made wrong choose.'        print """            (C)reate a file.            (D)isplay the file.            (E)dit the file.            (S)ave the file.            (Q)uit"""        choose = raw_input("Please input your choose:").lower()if __name__ == '__main__':    main()
#9-17# '''搜索文件. 提示输入一个字节值(0 - 255)和一个文件名. 显示该字符在文件中出现# 的次数.'''#def count_b():    count = 0    letter = chr(int(raw_input('Please input byte value(0-255):')))    filename = raw_input('Please input the file name:')    with open(filename,'r') as f:        for line in f:            count = count +line.count(letter)    print 'There are %d letter %c in file %s'%(count,letter,filename)#9-18'''创建文件. 创建前一个问题的辅助程序. 创建一个随机字节的二进制数据文件, 某一特定字节会在文件中出现指定的次数. 该程序接受三个参数:1) 一个字节值( 0 - 255 ),2) 该字符在数据文件中出现的次数, 以及3) 数据文件的总字节长度'''import randomdef create_file(bvalue, times, total_length):    byte_list = []    for i in range(times):        byte_list.append(bvalue)    while(len(byte_list)<=total_length):        letter = chr(random.choice(xrange(255))) #字节值转换为字符        if letter != bvalue:            byte_list.append(letter)    print byte_list    random.shuffle(byte_list) #打乱列表    print byte_list    with open('d.txt', 'w') as f:        for eachline in byte_list:            f.write(eachline)def main():    bvalue = chr(int(raw_input('Please input byte value(0-255):')))    print bvalue    times = int(raw_input('How many times it appears:'))    total_length = int(raw_input('Please input total length of the file:'))    create_file(bvalue, times, total_length)    count_b()if __name__ == '__main__':    main()
#9-20'''压缩文件. 写一小段代码, 压缩/解压缩 gzip  bzip 格式的文件. 可以使用命令行下的 gzip  bzip2 以及 GUI 程序 PowerArchiver , StuffIt ,  WinZip 来确认你的 Python支持这两个库.'''import gzipimport bz2def compress_gzip(filename, gzipname):    with open(filename, 'rU') as fn:        with gzip.open(gzipname, 'wb') as gn:            in2out(fn, gn)        gn.close()    fn.close()def decompress_gzip(filename, gzipname):    with gzip.open(gzipname, 'rb') as gn:        with open(filename, 'w') as fn:            in2out(gn, fn)        fn.close()    gn.close()def compress_bzip2(filename, bzip2name):    with open(filename, 'rU') as fn:        with bz2.BZ2File(bzip2name, 'wb') as gn:            in2out(fn, gn)        gn.close()    fn.close()def decompress_bzip2(filename, bzip2name):    with bz2.BZ2File(bzip2name, 'rb') as gn:        with open(filename, 'w') as fn:            in2out(gn, fn)        fn.close()    gn.close()def newname(src): #重新命名文件    string = src.split('.')    newsrc = string[0]+'new.'+string[1]    return newsrcdef in2out(fn, gn):    for eachline in fn:        gn.write(eachline)def main():    src = '58.log'    src2 = 'b.txt'    dst = '58.log.gz'    dst2 = '58.log.bz2'    compress_gzip(src, dst)#压缩txt文件的换行符问题暂时没解决    decompress_gzip(newname(src), dst)    compress_bzip2(src, dst2)    decompress_bzip2(newname(src2), dst2)if __name__ == '__main__':    main()




原创粉丝点击