Python一日一练03----输出网页

要求

将以下文档作为网页模版,编程实现由用户定义网页信息并将网页输出保存

<?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 datetime
import xml.sax.saxutils

COPYRIGHT_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"}):
            break

def 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()方法

时间: 2024-10-03 06:25:34

Python一日一练03----输出网页的相关文章

Python一日一练102----创建简易博客(下)

继续改博客 接着上一篇继续改咱的博客. 母语不是英语肿么办,博客上面英语好多啊! 更改很简单. 你可以做一个快速更改来观察Django管理工具是否被翻译成你想要的语言. 仅需在settings.py添加'django.middleware.locale.LocaleMiddleware' 到MIDDLEWARE_CLASSES设置中,并确保它在'django.contrib.sessions.middleware.SessionMiddleware'之后就可以了. 建立博客的前台部分 创建模版

Python一日一练01----字符输出

要求 编写一个程序,当输入python bigdigists.py 234234,会输出下列结果. 源码 import sys Zero = ["  ***  ",         " *   * ",         "*     *",         "*     *",         "*     *",         " *   * ",         "  *

Python一日一练103----Django模版练习

要求 request.META 是一个Python字典,包含了所有本次HTTP请求的Header信息,比如用户IP地址和用户Agent.通过request.META.items()可得到这个字典.要求将META信息输出到网页. 输出结果 源码 index.html <html> <head><title>{{index_title}}</title></head> <body> {% block mainbody %} {%for k

Python一日一练05----怒刷点击量

功能 自己主动获取CSDN文章列表,并对每篇文章添加点击量. 源代码 import urllib.request import re import time import random from bs4 import BeautifulSoup p = re.compile('/a359680405/article/details/........') #自己的博客主页 url = "http://blog.csdn.net/a359680405" #使用build_opener()是

Python一日一练06----怒刷点击量pyqt5版

功能 输入博主用户名,增加博主点击量 软件截图 部分源码 # coding=utf-8 __author__ = 'a359680405' from PyQt5 import QtWidgets from PyQt5.QtCore import QThread from PyQt5.QtCore import pyqtSignal from visitspage.UI.MainForm import Ui_MainForm from visitspage.UI.newForm import Ui

Python 一日一练: 01

将数字转换为LCD模式 代码如下: 1 # -*- coding:utf-8 -*- 2 ''' 3 Python 小练习-1 : 将数字转换为LCD显示 4 ''' 5 lt = [' __ ', '|__ ', '|__|', ' |', ' __|', '| |', ' '] 6 dt = {0:[0, 5, 2],1:[6, 3, 3], 2:[0, 4, 1], 3:[0, 4, 4], 4:[6, 2, 3], 5:[0, 1, 4], 6:[0, 1, 2], 7:[0, 3, 3

Python一日一练104----Django URLconf练习

要求 请实现当url是http://127.0.0.1:8000/sum/n/(n是数字)时,返回的页面显示1-n的累加和的结果. 源码 views.py文件 #coding:utf-8 from django.shortcuts import render from django.http import HttpResponse,Http404 # Create your views here. def num_plus(request,plus): try: plus=int(plus) e

Python一日一练03----一元二次方程的计算

要求 由用户随意给定一元二次方程系数a.b.c,计算一元二次方程的解 源码 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: #sys.float_info.epsilon是浮点数0

Python一日一练02----诗词生成器

要求 编写一段程序,可以自动生成小诗. 格式如下 源码 import random import sys articles = ["the", "a", "another", "her", "his"] subjects = ["cat", "dog", "horse", "man", "woman", &q