【python】为markdown自动生成目录

markdown很优雅,但层级一多浏览起来就不够优雅了。
我们需要可跳转的目录,这样就可以随时按home键回到目录,再跳转到文章的任意部分。
结合[name](#hid)<h1 id=hid>name</h1>可以做出可跳转的目录列表,但一个个做就有点麻烦。
这个脚本能生效的前提是标题书写符合规范,即若干个#加上若干个空格,当然,也可以修改文件头部正则匹配的pattern。
目录效果可以参照这篇文章,当然,自定义也很简单。
GitHub上可获取最新版本。

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

            
          
          
posted @ 2017-06-26 23:43  findneo  阅读(2005)  评论(0编辑  收藏  举报