listing22-2.py

来自「《Beginning Python--From Novice to Profes」· Python 代码 · 共 30 行

PY
30
字号
from xml.sax.handler import ContentHandlerfrom xml.sax import parseclass PageMaker(ContentHandler):    passthrough = False    def startElement(self, name, attrs):        if name == 'page':            self.passthrough = True            self.out = open(attrs['name'] + '.html', 'w')            self.out.write('<html><head>\n')            self.out.write('<title>%s</title>\n' % attrs['title'])            self.out.write('</head><body>\n')        elif self.passthrough:            self.out.write('<' + name)            for key, val in attrs.items():                self.out.write(' %s="%s"' % (key, val))            self.out.write('>')    def endElement(self, name):        if name == 'page':            self.passthrough = False            self.out.write('\n</body></html>\n')            self.out.close()        elif self.passthrough:            self.out.write('</%s>' % name)    def characters(self, chars):        if self.passthrough: self.out.write(chars)parse('website.xml', PageMaker ())

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?