python challenge level 6 url: http://www.pythonchallenge.com/pc/def/channel.html
我以前没用过zipfile这个模块,所以决定先把level6放一放,把前面的blog先补起来,之后再完成level6和level6的blog,所以在今天之前,level6都只完成了一半。
言归正传,level6的页面还是那么朴素,甚至可以说比以前更朴素,果然还是得深入探讨页面源代码啊~这次的源代码中有两处注释,第二处的注释对于解题毫无作用,直接pass掉,那么这一题的着手点就是第一处的注释了。这一处的注释内容为“<-- zip”,再往前一点就会发现完整的信息:“html<--zip”,也就是说把html替换成zip,所以我们就可以得到一个叫作“channel.zip”的文件。图片加上zip文件,很明显这一题跟zip脱不了关系了,甚至很可能用到有关zip的模块。
是否用到有关zip的模块先不管,还是先看看压缩文件里都有那些内容吧,解压之后会发现一堆以数字命名、以txt结尾的文件,再加上一个readme文件,那么,当然要先看看readme会告诉我们那些信息。readme给了我们两个提示:
由于第二条不知道到底是指什么,而其余的txt文件几乎都是“Next nothing is ***”的形式,所以决定先从90052开始遍历文件,看看最后能够得到什么。
#! /usr/bin/env python '''python challenge level 6 question url: http://www.pythonchallenge.com/pc/def/channel.html ''' name = '90052.txt' while True: f = open('level6.d/%s' % name) data = f.read().split()[-1] f.close() if data.isdigit(): name = '%s.txt' % data else: break f = open('level6.d/%s' % name) print f.read() f.close()
其实也可以用正则表达式来求data,不过代码稍微长一点,至于两种方法的效率谁好一些我就不清楚了。最后的到的结果是:“Collect the comments.”。好吧,果然还是要使用zip相关的模块。今天吃完饭抽时间看了一下zipfile模块,然后完成了这一题。
#! /usr/bin/env python '''python challenge level 6 question url: http://www.pythonchallenge.com/pc/def/channel.html ''' import zipfile zf = zipfile.ZipFile('level6.d/channel.zip') zc = [] name = '90052.txt' while True: f = open('level6.d/%s' % name) data = f.read().split()[-1] f.close() zc.append(zf.getinfo(name).comment) if data.isdigit(): name = '%s.txt' % data else: break print ''.join(zc)
后来闲得蛋疼又写了一个纯读取zip文件的版本:
#! /usr/bin/env python '''python challenge level 6 question url: http://www.pythonchallenge.com/pc/def/channel.html ''' import re findnum = re.compile(r'\d+$').findall import zipfile zf = zipfile.ZipFile('level6.d/channel.zip') zc=[] name = '90052.txt' while True: zinfo = zf.getinfo(name) z = zf.open(name) data = findnum(z.read()) z.close() zc.append(zinfo.comment) if data: name = '%s.txt' % data[0] else: break print ''.join(zc)
赶紧把channel换成hockey,结果被告知去看一下使用的字母,好吧,oxygen,这回没错了,下一题的链接为:http://www.pythonchallenge.com/pc/def/oxygen.html。
看了看下一题的页面和源代码,这一题肯定要处理图像,这我可不会,回去研究一下,过段时间再来挑战。