《Python3程序开发指南(第二版)》第2章 数据类型 练习
来源:互联网 发布:象印保温杯涂层 知乎 编辑:程序博客网 时间:2024/06/06 04:34
1.修改程序print_unicode.py,以便用户可以在命令行上输入几个单独的单词,并且只有在Unicode字符名包含用户所指定的所有单词时才打印相应列。
__author__ = 'Ibuki Suika'import sysimport unicodedatadef print_unicode_table(words): print("decimal hex chr {0:^40}".format("name")) print("------- ----- --- {0:-<40}".format("")) code = ord(" ") end = min(0xD800, sys.maxunicode) while code < end: c = chr(code) name = unicodedata.name(c, "*** unknown ***") b = True for word in words: if word.lower() not in name.lower(): b = False break if b: print("{0:7} {0:5X} {0:^3c} {1}".format(code, name.title())) code += 1words = []if len(sys.argv) > 1: if sys.argv[1] in ("-h", "--help"): print("usage: {0} [string]".format(sys.argv[0])) word = None else: words = sys.argv[1:]if words is not None: print_unicode_table(words)2.修改quadratic.py,使得系数0.0对应的方程项不再输出,负数系数的输出形式为-n,而不是+-n。
__author__ = 'Ibuki Suika'import cmathimport mathimport sysdef get_float(msg, allow_zero): x = None while x is None: try: x = float(input(msg)) if not allow_zero and abs(x) < sys.float_info.epsilon: print("zero is not allowed") x = None except ValueError as err: print(err) return xprint("ax\N{SUPERSCRIPT TWO} + bx + c = 0")a = get_float("enter a: ", False)b = get_float("enter b: ", True)c = get_float("enter c: ", True)x1 = Nonex2 = Nonediscriminant = (b ** 2) - (4 * a * c)if discriminant == 0: x1 = -(b / (2 * a))else: if discriminant > 0: root = math.sqrt(discriminant) else: root = cmath.sqrt(discriminant) x1 = (-b + root) / (2 * a) x2 = (-b - root) / (2 * a)equation = "{0}x\N{SUPERSCRIPT TWO}".format(a)if b != 0: equation += "{0:+}x".format(b)if c != 0: equation += "{0:+}".format(c)equation += "=0 \N{RIGHTWARDS ARROW} x = {0}".format(x1)if x2 is not None: equation += " or x = {0}".format(x2)print(equation)3.从csv2html.py程序中删除escape_html()函数,使用xml.sax.saxutils模块中的xml.sax.saxutils.escape() 函数替代地完成相关功能。
__author__ = 'Ibuki Suika'import sysfrom xml.sax.saxutils import escapedef main(): maxwidth = 100 print_start() count = 0 while True: try: line = input() if count == 0: color = "lightgreen" elif count % 2: color = "white" else: color = "lightyellow" print_line(line, color, maxwidth) count += 1 except EOFError: break print_end()def print_start(): print("<table border='1'>")def print_line(line, color, maxwidth): print("<tr bgcolor='{0}'>".format(color)) fields = extract_fields(line) for field in fields: if not field: print("<td></td>") else: number = field.replace(",", "") try: x = float(number) print("<td align='right'>{0:d}</td>".format(round(x))) except ValueError: field = field.title() field = field.replace(" And ", " and ") if len(field) <= maxwidth: field = escape(field) else: field = "{0} ...".format(escape(field[:maxwidth])) print("<td>{0}</td>".format(field)) print("</tr>")def extract_fields(line): fields = [] field = "" quote = None for c in line: if c in "\"'": if quote is None: # start of quoted string quote = c elif quote == c: # end of quoted string quote = None else: field += c # other quote inside quoted string continue if quote is None and c == ",": # end of a field fields.append(field) field = "" else: field += c # accumulating a field if field: fields.append(field) # adding the last field return fieldsdef print_end(): print("</table>")main()4.再次对csv2html.py进行修改,这次要求添加一个名为process_options()的新函数。这一函数应该从main()中进行调用,并返回一个两元组:maxwidth(int型)和format(str型)。
import sysimport xml.sax.saxutilsdef main(): maxwidth, format = process_options() if maxwidth is not None: print_start() count = 0 while True: try: line = input() if count == 0: color = "lightgreen" elif count % 2: color = "white" else: color = "lightyellow" print_line(line, color, maxwidth, format) count += 1 except EOFError: break print_end()def process_options(): maxwidth_arg = "maxwidth=" format_arg = "format=" maxwidth = 100 format = ".0f" for arg in sys.argv[1:]: if arg in ["-h", "--help"]: print("""\usage:csv2html.py [maxwidth=int] [format=str] < infile.csv > outfile.htmlmaxwidth is an optional integer; if specified, it sets the maximumnumber of characters that can be output for string fields,otherwise a default of {0} characters is used.format is the format to use for numbers; if not specified itdefaults to "{1}".""".format(maxwidth, format)) return None, None elif arg.startswith(maxwidth_arg): try: maxwidth = int(arg[len(maxwidth_arg):]) except ValueError: pass elif arg.startswith(format_arg): format = arg[len(format_arg):] return maxwidth, formatdef print_start(): print("<table border='1'>")def print_line(line, color, maxwidth, format): print("<tr bgcolor='{0}'>".format(color)) numberFormat = "<td align='right'>{{0:{0}}}</td>".format(format) fields = extract_fields(line) for field in fields: if not field: print("<td></td>") else: number = field.replace(",", "") try: x = float(number) print(numberFormat.format(x)) except ValueError: field = field.title() field = field.replace(" And ", " and ") if len(field) <= maxwidth: field = xml.sax.saxutils.escape(field) else: field = "{0} ...".format( xml.sax.saxutils.escape(field[:maxwidth])) print("<td>{0}</td>".format(field)) print("</tr>")def extract_fields(line): fields = [] field = "" quote = None for c in line: if c in "\"'": if quote is None: quote = c elif quote == c: quote = None else: field += c continue if quote is None and c == ",": fields.append(field) field = "" else: field += c if field: fields.append(field) return fieldsdef print_end(): print("</table>")main()
0 0
- 《Python3程序开发指南(第二版)》第2章 数据类型 练习
- 《Python3程序开发指南(第二版)》第3章 组合数据类型 练习
- 《Python3程序开发指南(第二版)》第1章 过程型程序设计快速入门 练习
- 《Python3程序开发指南(第二版)》第4章 控制结构与函数 练习
- 《Python3程序开发指南(第二版)》第5章 模块 练习
- python3程序开发指南——第1章 笔记
- Python3程序开发指南(中文版第二版) PDF分享 百度云
- Android编程权威指南(第二版)— 第10章挑战练习
- Android编程权威指南(第二版)— 第13章挑战练习-13.6
- Android编程权威指南(第二版)— 第13章挑战练习-13.8
- Python3程序开发指南(第三版)学习笔记
- 《Python3程序开发指南》02:文件的写入(简单)
- 《Android编程权威指南》第二版 第二章 挑战练习
- Android编程权威指南(第2版)第1/2章中的挑战练习思路
- Android编程权威指南(第2版)—第2章挑战练习
- Android编程权威指南(第2版)—第6章挑战练习
- Android编程权威指南(第2版)—第5章挑战练习
- Android编程权威指南(第2版)—第8章挑战练习
- 原生JS省市县三级联动菜单
- 6.9引蜘蛛。五
- 6.9引蜘蛛。六
- 6.9引蜘蛛。七
- 判断浏览器是否全屏
- 《Python3程序开发指南(第二版)》第2章 数据类型 练习
- 6.9引蜘蛛。八
- 6.9引蜘蛛。久
- 我眼中的比特币应用前景
- 线性表的本质和相关操作
- 用jquery实现隐藏列表表单的显示关闭切换以及Ajax方式修改提交对应的那一行的修改内容。
- Android应用程序实现自动更新功能1_服务器端配置
- http://blog.csdn.net/jiangzhaobao/article/details/7968403
- 6.9引蜘蛛。十一