Python一日一練03----輸出網頁,python03----

來源:互聯網
上載者:User

Python一日一練03----輸出網頁,python03----


要求將以下文檔作為頁面範本,編程實現由使用者定義網頁資訊並將網頁輸出儲存

<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" \
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>{title}</title>
<!-- {copyright} -->
<meta name="Description" content="{description}" />
<meta name="Keywords" content="{keywords}" />
<meta equiv="content-type" content="text/html; charset=utf-8" />
{stylesheet}\
</head>
<body>
</body>
</html>


源碼

import datetimeimport xml.sax.saxutilsCOPYRIGHT_TEMPLATE = "Copyright (c) {0} {1}. All rights reserved."STYLESHEET_TEMPLATE = ('<link rel="stylesheet" type="text/css" '                       'media="all" href="{0}" />\n')HTML_TEMPLATE = """<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><title>{title}</title><!-- {copyright} --><meta name="Description" content="{description}" /><meta name="Keywords" content="{keywords}" /><meta equiv="content-type" content="text/html; charset=utf-8" />{stylesheet}\</head><body></body></html>"""class CancelledError(Exception): pass                                   #自訂異常def main():    information = dict(name=None, year=datetime.date.today().year,                       filename=None, title=None, description=None,                       keywords=None, stylesheet=None)    while True:        try:            print("\nMake HTML Skeleton\n")            populate_information(information)                           #注意兩種參數用法的異同            make_html_skeleton(**information)                           #注意兩種參數用法的異同        except CancelledError:            print("Cancelled")        if (get_string("\nCreate another (y/n)?", default="y").lower()            not in {"y", "yes"}):            breakdef populate_information(information):    name = get_string("Enter your name (for copyright)", "name",                      information["name"])    if not name:        raise CancelledError()    year = get_integer("Enter copyright year", "year",                       information["year"], 2000,                       datetime.date.today().year + 1, True)    if year == 0:        raise CancelledError()                                           #彈出異常    filename = get_string("Enter filename", "filename")    if not filename:        raise CancelledError()    if not filename.endswith((".htm", ".html")):        filename += ".html"    title = get_string("Enter title", "title")    if not title:        raise CancelledError()    description = get_string("Enter description (optional)",                             "description")    keywords = []    while True:        keyword = get_string("Enter a keyword (optional)", "keyword")        if keyword:            keywords.append(keyword)        else:            break    stylesheet = get_string("Enter the stylesheet filename "                            "(optional)", "stylesheet")    if stylesheet and not stylesheet.endswith(".css"):        stylesheet += ".css"    information.update(name=name, year=year, filename=filename,                       title=title, description=description,                       keywords=keywords, stylesheet=stylesheet)def make_html_skeleton(year, name, title, description, keywords,                       stylesheet, filename):    copyright = COPYRIGHT_TEMPLATE.format(year,                                    xml.sax.saxutils.escape(name))#xmlsax.saxutils.escape()函數,接受一個字串,並返回一個帶有html字元的字串("&"、"<"、">"分別以轉義符"&"、"<"、"$gt;"的形式出現)    title = xml.sax.saxutils.escape(title)                              description = xml.sax.saxutils.escape(description)    keywords = ",".join([xml.sax.saxutils.escape(k)                 #將排列變成字串,並用逗號隔開                         for k in keywords]) if keywords else ""    stylesheet = (STYLESHEET_TEMPLATE.format(stylesheet)                  if stylesheet else "")    html = HTML_TEMPLATE.format(**locals())    fh = None    try:        fh = open(filename, "w", encoding="utf8")        fh.write(html)    except EnvironmentError as err:        print("ERROR", err)    else:        print("Saved skeleton", filename)    finally:        if fh is not None:            fh.close()def get_string(message, name="string", default=None,               minimum_length=0, maximum_length=80):    message += ": " if default is None else " [{0}]: ".format(default)    while True:        try:            line = input(message)            if not line:                if default is not None:                    return default                if minimum_length == 0:                    return ""                else:                    raise ValueError("{0} may not be empty".format(                                     name))            if not (minimum_length <= len(line) <= maximum_length):                raise ValueError("{name} must have at least "                        "{minimum_length} and at most "                        "{maximum_length} characters".format(                        **locals()))            return line        except ValueError as err:            print("ERROR", err)def get_integer(message, name="integer", default=None, minimum=0,                maximum=100, allow_zero=True):    class RangeError(Exception): pass    message += ": " if default is None else " [{0}]: ".format(default)    while True:        try:            line = input(message)            if not line and default is not None:                return default            i = int(line)            if i == 0:                if allow_zero:                    return i                else:                    raise RangeError("{0} may not be 0".format(name))            if not (minimum <= i <= maximum):                raise RangeError("{name} must be between {minimum} "                        "and {maximum} inclusive{0}".format(                        " (or 0)" if allow_zero else "", **locals()))            return i        except RangeError as err:            print("ERROR", err)        except ValueError as err:            print("ERROR {0} must be an integer".format(name))main()


出現的問題與用的的知識點Python菜鳥晉級08----str.format()方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.