《Python核心编程》答案 第9章
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《Python核心编程》答案 第9章相关的知识,希望对你有一定的参考价值。
9-1:
filename = raw_input() f = open(filename) for eachLine in f: if eachLine[0] == ‘#‘: continue print eachLine, f.close()
附加题:
filename = raw_input() f = open(filename) for eachLine in f: if ‘#‘ not in eachLine: print eachLine, elif eachLine[0] == ‘#‘: continue else: ans = "" for i in eachLine: if i == ‘#‘: break ans += i print ans f.close()
9-2:
print ‘Please input number N and file F, we will display first N lines for your file‘ n = int(raw_input(‘N: ‘)) fname = raw_input(‘F: ‘) f = open(fname) for eachLine in f: if n == 0: break print eachLine, n -= 1 f.close()
9-3:
print ‘Enter a filename, we will display the number of lines of this file.‘ fname = raw_input() f = open(fname) count = 0 for eachLine in f: count += 1 print ‘This file has %d line(s).‘ % count f.close()
9-4:
fname = raw_input(‘Enter a filename: ‘) f = open(fname) count = 0 for eachLine in f: count += 1 print eachLine, if count % 25 == 0: raw_input(‘Press anykey to continue‘) f.close()
9-5:
fname = raw_input() f = open(fname) sum_of_score = 0.0 count = 0 for eachLine in f: sum_of_score += float(eachLine) count += 1 avg_of_score = sum_of_score / count if 90 <= avg_of_score <= 100: print ‘A‘ elif 80 <= avg_of_score <= 89: print ‘B‘ elif 70 <= avg_of_score <= 79: print ‘C‘ elif 60 <= avg_of_score <= 69: print ‘D‘ else: print ‘F‘
9-6:
print ‘Enter two file name to compare (suppose two file has same rows)‘ f1name = raw_input(‘file A: ‘) f2name = raw_input(‘file B: ‘) f1 = open(f1name) f2 = open(f2name) line = 0 same = True for eachLine in f1: line += 1 f2Line = f2.next() if eachLine == f2Line: continue else: same = False col = 0 for i in eachLine: if i != f2Line[col]: break col += 1 col += 1 break if same: print ‘Two files are the same‘ else: print ‘The first different occurs %d line %d column.‘ % (line, col)
9-7:
f = open(‘/etc/services‘) print ‘%17s\t%5s\t%5s‘ % (‘name‘, ‘port‘, ‘protocol‘) for eachLine in f: if eachLine[0] in (‘#‘, ‘\n‘): continue data = eachLine.split() name = data[0] port = data[1].split(‘/‘)[0] protocol = data[1].split(‘/‘)[1] print ‘%17s\t%5s\t%5s‘ % (name, port, protocol) f.close()
9-8:
mname = raw_input(‘Enter a module name: ‘) exec compile(‘import ‘ + mname, ‘‘, ‘single‘) exec compile(‘a = dir(‘+mname+‘)‘, ‘‘, ‘single‘) print "The attributes of", mname print ‘%10s\t%10s\t%10s‘ % (‘name‘, ‘type‘, ‘value‘) for eachAttr in a: exec compile(‘value = ‘ + mname + ‘.‘ + eachAttr, ‘‘, ‘single‘) print ‘%10s\t%10s\t%10s‘ % (eachAttr, type(eachAttr), value)
9-9:稍后更新
9-10:稍后更新
9-11:
(a)
import os print ‘Welcome URL bookmark manager‘ hasdata = False if os.path.exists(‘data.txt‘): datafile = open(‘data.txt‘, ‘r+‘) hasdata = True else: datafile = open(‘data.txt‘, ‘w‘) prompt = """ (A)dd (U)pdate (D)elete (S)earch (Q)uit select one: """ data = [] if hasdata: temp = datafile.read().split(‘\n‘) for t in temp: data.append(t.split(‘ ‘)) while True: option = raw_input(prompt).lower()[0] if option == ‘a‘: site_name = raw_input(‘Site name: ‘) url_address = raw_input(‘URL address: ‘) description = raw_input(‘One line description(optional): ‘) data.append([site_name, url_address, ‘"‘+description+‘"‘]) elif option == ‘u‘: site_name = raw_input(‘Enter the site name you want to update its url: ‘) url_address = raw_input(‘New url: ‘) for eachData in data: if eachData[0] == site_name: eachData[1] = url_address print ‘update succeed‘ break else: print ‘no such site name‘ elif option == ‘d‘: site_name = raw_input(‘Enter the site name you want to delete: ‘) for i in range(len(data)): if data[i][0] == site_name: del data[i] print ‘delete succeed‘ break else: print ‘no such site name‘ elif option == ‘s‘: keyword = raw_input(‘Enter the keyword in site name or url address: ‘) findit = False for eachData in data: for eachItem in eachData: if keyword in eachItem: print ‘Site name: %s, URL address: %s, description: %s‘ % (eachData[0],eachData[1],eachData[2]) findit = True break if findit: break if not findit: print ‘cannot find %s‘ % keyword elif option == ‘q‘: ans = [] for eachData in data: ans.append(‘ ‘.join(eachData)) ans = ‘\n‘.join(ans) datafile.seek(0) datafile.truncate() datafile.write(ans) datafile.close() break
(b)稍后更新
9-12:稍后更新
9-13:
(a)
命令行参数是调用某个程序时除程序名以外的其他参数。Unix操作系统中的命令通常会接受输入,执行一些功能,然后把结果作为流输出出来。命令行参数使程序员可以在启动一个程序的时候对程序行为做出选择。
(b)
from sys import argv print "# of args", len(sys.argv) print "args:", sys.argv
9-14:
from sys import argv if len(argv) == 2: f = open(‘data.txt‘, ‘r+‘) for eachLine in f: print eachLine, f.seek(0) f.truncate() f.close() else: n1 = argv[1] n2 = argv[3] op = argv[2] if op == ‘+‘: ans = float(n1) + float(n2) elif op == ‘-‘: ans = float(n1) - float(n2) elif op == ‘*‘: ans = float(n1) * float(n2) elif op == ‘/‘: ans = float(n1) / float(n2) elif op in (‘**‘, ‘^‘): ans = float(n1) ** float(n2) if ans == int(ans): ans = int(ans) print ans f = open(‘data.txt‘, ‘a+‘) f.write(‘%s %s %s\n‘ % (n1, op, n2)) f.write(str(ans) + ‘\n‘) f.close()
9-15:
print ‘Input 2 file name, we will copy content from file1 to file2: ‘ f1name = raw_input(‘File 1: ‘) f2name = raw_input(‘File 2: ‘) f1 = open(f1name) f2 = open(f2name, ‘w‘) f2.write(f1.read())
9-16:
fname = raw_input(‘Enter file name: ‘) f = open(fname, ‘r+‘) content = f.readlines() index = 0 while True: if (len(content[index]) > 80) and (index < len(content)-1): content[index+1] = content[index][80:].strip() + content[index+1].strip() + ‘\n‘ content[index] = content[index][:80] + ‘\n‘ elif (len(content[index]) > 80) and (index >= len(content)-1): content.append(content[index][80:]) content[index] = content[index][:80] + ‘\n‘ index += 1 if index >= len(content): break f.seek(0) f.truncate() f.write(‘‘.join(content)) f.close()
9-17:
print ‘Welcome to crude and elementary text file editor‘ prompt = """ (C)reate file (D)isplay file (E)dit file (S)ave file (Q)uit select one: """ option = raw_input(prompt).lower()[0] content = [] while True: if option == ‘c‘: filename = raw_input(‘Enter the file name: ‘) print ‘Please enter file content, end with ctrl+c‘ try: while True: content.append(raw_input(‘->‘)) except KeyboardInterrupt: print ‘create succeed!‘ elif option == ‘d‘: for eachLine in content: print eachLine elif option == ‘e‘: line = int(raw_input(‘Which line you want to edit? ‘)) print ‘The new content:‘ ncontent = raw_input(‘->‘) content[line-1] = ncontent elif option == ‘s‘: f = open(filename, ‘w‘) f.write(‘\n‘.join(content)) f.close() elif option == ‘q‘: break else: print ‘error option‘ option = raw_input(prompt).lower()[0]
9-18:
print ‘Enter a byte value(0-255) and a filename‘ print ‘We will display the number of times that byte appers in the file.‘ value = int(raw_input(‘Byte value(0-255): ‘)) fname = raw_input(‘Filename: ‘) f = open(fname) ch = chr(value) count = 0 for each in f.read(): if each == ch: count += 1 print "The byte value %d(‘%s‘) appears %d times in this file."% (value, ch, count) f.close()
9-19:
from random import randint def mybin(n): ans = ‘‘ while n != 0: ans = str(n % 2) + ans n = n / 2 for i in range(8-len(ans)): ans = ‘0‘ + ans return int(ans) byte_value = int(raw_input(‘Byte value: ‘)) times = int(raw_input(‘Times: ‘)) total_byte = int(raw_input(‘Total byte: ‘)) ans = [] for i in range(total_byte - times): num = byte_value while num == byte_value: num = randint(0,255) num = mybin(num) ans.append(str(num)) byte_value = mybin(byte_value) for i in range(times): position = randint(0, total_byte - times) ans.insert(position, str(byte_value)) ans = ‘ ‘.join(ans) f = open(‘data.txt‘, ‘w‘) f.write(ans) f.close()
9-20 ~ 9-25:稍后更新
以上是关于《Python核心编程》答案 第9章的主要内容,如果未能解决你的问题,请参考以下文章