1. 程式人生 > >《Python3程式開發指南(第二版)》第2章 資料型別 練習

《Python3程式開發指南(第二版)》第2章 資料型別 練習

1.修改程式print_unicode.py,以便使用者可以在命令列上輸入幾個單獨的單詞,並且只有在Unicode字元名包含使用者所指定的所有單詞時才打印相應列。

__author__ = 'Ibuki Suika'

import sys
import unicodedata

def 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 += 1

words = []
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 cmath
import math
import sys


def 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 x


print("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 = None
x2 = None
discriminant = (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 sys
from xml.sax.saxutils import escape


def 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 fields


def print_end():
    print("</table>")


main()
4.再次對csv2html.py進行修改,這次要求新增一個名為process_options()的新函式。這一函式應該從main()中進行呼叫,並返回一個兩元組:maxwidth(int型)和format(str型)。
import sys
import xml.sax.saxutils


def 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.html

maxwidth is an optional integer; if specified, it sets the maximum
number 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 it
defaults 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, format


def 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 fields


def print_end():
    print("</table>")


main()