Python一日一练03----输出网页
来源:互联网 发布:gossip算法 编辑:程序博客网 时间:2024/05/01 06:37
要求
将以下文档作为网页模版,编程实现由用户定义网页信息并将网页输出保存<?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()方法
欢迎收听我的微信公众号
1 0
- Python一日一练03----输出网页
- Python一日一练01----字符输出
- Python一日一练03----一元二次方程的计算
- Python一日一练100----消息服务器
- Python一日一练02----诗词生成器
- Python一日一练07----冒泡排序
- Python一日一练08----鸡尾酒排序
- Python一日一练09----奇偶排序
- Python一日一练10----快速排序
- Python一日一练11----选择排序
- Python一日一练12----堆排序
- Python一日一练13----插入排序
- Python一日一练14----希尔排序
- Python一日一练15----归并排序
- Python一日一练16----折半查找
- Python一日一练103----Django模版练习
- Python一日一练104----Django URLconf练习
- Python一日一练102----创建简易博客(下)
- Windows Azure 云端初体验
- html的图片处理
- IE开发者工具教程
- eclipse+ADT 进行android应用签名打包详解
- 如何实现Show In Finder的选中并打开所在目录
- Python一日一练03----输出网页
- 大数据量的系统的数据库结构如何设计
- find && mv
- 闲时整理(5)--圆形标签
- 飞思卡尔MX51上的FB 分析
- 用HTML和CSS构建3D世界
- tomcat server.xml 介绍
- Freescale关于USB BDM MULTILINK调试器使用说明
- 软中断,tasklet和工作队列的区别与联系