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()