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

            
          
          


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM