其实对于这个python小项目我感触的也不算很深刻,因为总是感觉和项目一比较相似。比如说
def dispatch(self, prefix, name, attrs=None):
mname = prefix + name.capitalize()
dname = 'default' + prefix.capitalize()
method = getattr(self, mname, None)
if callable(method): args = () #judgement method
else:
method = getattr(self, dname, None)
args = name,
if prefix == 'start':args += attrs,
if callable(method): method(*args) #arguement not less than zero
def startElement(self, name, attrs):
self.dispatch('start', name, attrs)
def endElement(self, name):
self.dispatch('end', name)
这段程序确实很经典,经典之处就在于可以省去大量的if语句。这段程序是这样构造的:首先获取组合函数名(mname,dname),然后判断是否存在这样的函数(callable),存在就是startname,endname否则是defaultname.
对于类WebsiteConstructor:
class WebsiteConstructor(Dispatcher, ContentHandler):
passthrough = False
def __init__(self, directory):
self.directory = [directory]
self.ensureDirectory()
def ensureDirectory(self):
path = os.path.join(*self.directory)
if not os.path.isdir(path): os.makedirs(path) #set dir
def characters(self, chars):
if self.passthrough:
self.out.write(chars)
def defaultStart(self, name, attrs):
if self.passthrough:
self.out.write('<' + name)
for key, val in attrs.items():
self.out.write(' %s="%s"' %(key, val))
self.out.write('>')
def defaultEnd(self, name):
if self.passthrough:
self.out.write('</%s>' % name)
def startDirectory(self, attrs):
self.directory.append(attrs['name']) #########importent attrs['name'] is 'name'
self.ensureDirectory()
def endDirectory(self):
self.directory.pop()
def startPage(self, attrs):
filename = os.path.join(*self.directory+[attrs['name']+'.html'])
self.out = open(filename, 'w')
self.writeHeader(attrs['title']) ########importent attrs['title'] is 'title'
self.passthrough = True
def endPage(self):
self.passthrough = False
self.writeFooter()
self.out.close()
def writeHeader(self, title):
self.out.write('<html>\n <head>\n <title>')
self.out.write(title)
self.out.write('</title>\n </head>\n <body>\n')
def writeFooter(self):
self.out.write('\n </body>\n</html>\n')
就是响应dispatch函数的,这里我想说说整个程序运行顺序如果有不对的地方请给我留言:
首先是从这个开始的
parse('website.xml', WebsiteConstructor('public_html'))
然后是进入WebsiteConstructor中,首先执行__init__函数创建public_html目录,然后开始startElement函数,并调用dispatch判断WebsiteConstructor是否有所需的函数,判断后进行程序运行其中如何name为directory则创建目录否则就在文档里面写入语句,对于在文档中写入语句的多少依据passthrough判断。控制函数为characters函数。
总得合在一起就生成了整个程序需要的结果:
public_html/
public_html/index.html
public_html/interests
public_html/interests/shouting.html
public_html/interests/sleep.html
public_html/interests/eating