《Python核心编程》第九章编程题代码

来源:互联网 发布:uygurqa mp3 下载软件 编辑:程序博客网 时间:2024/06/08 18:28

9.1

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-f = open('test.txt','r')for eachline in f :    if(eachline[0] != '#') :        print eachline,

9.2

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-N = int(raw_input('input the line:> '))F = raw_input('input the filename:>')f = open(F,'r')for index,eachline in enumerate(f) :    if(index != N):        print eachline,    else :        break

9.3

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-filename = raw_input("input the filename:> ")f = open(filename,'r')count = 0for eachline in f :    count += 1print count

9.4

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-import msvcrtfilename = raw_input("input the filename :>")f = open(filename,'r')for index,eachline in enumerate(f):    print eachline,    if((index+1) % 25 == 0) :        input = raw_input('input any keyword to continue:> ')        if(input != None) :            continue

9.5

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-fname = open('usrname.txt','r')fmath = open('math.txt','r')fchinese = open('chinese.txt','r')fenglish = open('English.txt','r')usrlist = []mathlist = []chinese = []english = []index = 0for eachline in fname :    usrlist.append(eachline)for eachline in fmath :    mathlist.append(eachline)for eachline in fenglish :    english.append(eachline)for eachline in fchinese :    chinese.append(eachline)print '''usrname    mathgarde   english    chinese'''for index in range(0,len(usrlist)) :    print usrlist[index]+ mathlist[index]+chinese[index]+english[index],

9.8

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-name = raw_input("input the module name:>")obj = __import__(name)for item in dir(obj) :    print "name: ",item    print "type:",type(getattr(obj, item))    print "value:",getattr(obj,item)

9.9

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-from os import chdir, listdirpath = r'c:\python27\Lib'chdir(path)ls = [item for item in listdir(path) if item.endswith('.py')]db = {}.fromkeys(ls)#scan __doc__ in modulesfor item in ls:    with open(item) as f:        doc = ''        start = False        for line in f:            if line.strip().startswith('"""') and not start:                start = True                doc += line                if doc.strip().endswith('"""') and len(doc.strip()) > 3:                    start = False                    break            elif line.strip().endswith('"""'):                start = False                doc += line                break            elif start:                doc += line        db[item] = docempty = []full = []for key in sorted(db):    if db[key] == '':        empty.append(key)    else:        full.append(key)print 'moudles without doc:'for item in empty:    print item,printprint 'moudles with doc:'for item in full:    print item,printprint 'values:'for key in full:    print 'module: ', key    print 'doc: ', db[key]    print

9.12

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-import timedb = {}alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'def newuser() :    Lstring = 'Login name :'    login = False    while not login :       name = raw_input(Lstring)       for letter in name :           if letter not in alpha :               Lstring = 'Please input letters'               break       else :           for key in db.keys() :              if name.lower() == key.lower() :                 Lstring = 'name has existed , try another'                 break           else :                 pwd = raw_input('password : ')                 db[name] = pwd                 login = Truedef Loginuser() :    name = raw_input('name :')    time_string = []    if name in db :        print 'You have logged in this system,please input your password'        pwd= raw_input('password :')        if pwd == db.get(name) :           time_string.append(time.ctime())           print 'Welcome back' ,name,time_string[0]        else :           print 'Login incorrect'    else :        print 'You have not logged in this system,please log in it'        newuser()def deleteuser() :    Lstring = 'chose a delete user'    name = raw_input(Lstring)    if name in db :       del db[name]    else :        print 'unexisted user'def showalluser() :    for key in db.keys() :        print 'name = %s , password = %s' % (key,db[key])def showmenu() :    Lstring = """(N)ew User Login(E)xisting User Login(D)elete a user(S)how all user information(Q)uit    Enter choice :"""    done = False    while not done :        chosen = False        while not chosen :            try:                choice = raw_input(Lstring).strip()[0].lower()            except (EOFError,KeyboardInterrupt):                choice = 'q'            print '\nyou picked : [%s]' % choice            if choice not in 'neqds' :                print 'invalid option,try again'            else :                chosen = True        if choice == 'q' :            done = True        if choice == 'n' :            newuser()        if choice == 'e' :            Loginuser()        if choice == 'd' :            deleteuser()        if choice == 's' :            showalluser()showmenu()

9.14

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-import osimport sysdef calc(a,op,b) :   if(op == '+') :        return a + b   elif(op == '-') :       return a - b   elif(op == '*') :       return a * b   elif(op == '/') :       return a / b   elif(op == '^'):       return a ** bif(sys.argv[1] == 'input' ) :    if os.path.exists("jilu.txt"):       f = open("jilu.txt",'r')       for item in f :            print item       f.close()       os.remove("jilu.txt")    else :        f = open('jilu.txt','w')        f.close()        f = open("jilu.txt",'r')        for item in f :            print item        f.close()        os.remove("jilu.txt")else :    print calc(int(sys.argv[1]),sys.argv[2],int(sys.argv[3]))    s = sys.argv[1] + sys.argv[2]+sys.argv[3] +" = " +str(calc(int(sys.argv[1]),sys.argv[2],int(sys.argv[3])))    f = open("jilu.txt",'a+')    f.write("%s\n" % s)

9.15

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-filename1 = raw_input("input the filename : > ")filename2 = raw_input("input the filename : > ")f1 = open(filename1,'r')f2 = open(filename2,'w')for item in f1 :    f2.write(item)f2.close()f2 = open(filename2,'r')for item in f2 :    print item

9.16

__author__ = 'shiqifeng'#!/usr/bin/python# -*- coding: utf-8 -*-import osfile1 = raw_input("please enter the file: >")with open(file1) as fobj1:    with open("temp.txt","w") as fobj2:        for i in fobj1:            if len(i) > 80:                num = list(i)                count = len(num) / 80                for i in range(count):                    fobj2.write("".join(num[:79]))                    fobj2.write("\n")                    num = num[79:]                fobj2.write("".join(num))            else:                fobj2.write(i)                fobj2.write("\n")with open("temp.txt") as fobj2:    with open(file1,"w") as fobj1:        for i in fobj2:            fobj1.write(i)os.remove("temp.txt")
0 0