markdown很优雅,但层级一多浏览起来就不够优雅了。
咱们须要可跳转的目录,这样就能够随时按home键回到目录,再跳转到文章的任意部分。
结合[name](#hid)
和<h1 id=hid>name</h1>
能够作出可跳转的目录列表,但一个个作就有点麻烦。
这个脚本能生效的前提是标题书写符合规范,即若干个#
加上若干个空格,固然,也能够修改文件头部正则匹配的pattern。
目录效果能够参照这篇文章,固然,自定义也很简单。
在GitHub上可获取最新版本。html
#-*-coding:utf-8-*- import re,sys d={"#":1,"##":2,"###":3,"####":4,"#####":5,"######":6} pattern='#+\s' def usage(): print "usage:" print "python script.py srcFilename.md" print "then you will get a res.md with contents " print "under the same path as srcFile\nenjoy!" def ganMenu(filename): headId=0 targetname="res.md" with open(targetname,'w+') as f2: with open(filename,'r') as f: for i in f.readlines(): if not re.match(pattern,i.strip(' \t\n')): continue i=i.strip(' \t\n') head=i.split(' ')[0] f2.write('|'+'-----'*(len(head)-1)+'@['+i[len(head):].strip(' \t\n')+'](#id'+str(headId)+') \n') headId+=1 headId=0 with open(filename,'r') as f : for i in f.readlines(): if not re.match(pattern,i.strip(' \t\n')): f2.write(i) else: i=i.strip(' \t\n') head=i.split(' ')[0] if head in d.keys(): menu=''.join(['<h',str(len(head)),' id=id',str(headId),'>',i[len(head):].strip(' \t\n'),'</h',str(len(head)),'> \n']) f2.write(menu) headId+=1 if __name__ == '__main__': try: ganMenu(sys.argv[1]) except: usage()