#!/usr/local/bin/python # Takes a chapter as input and adds internal links and numbering to all # of the h1, h2, h3, h4 sections and so forth. # import sys import re if len(sys.argv) != 3: print "usage: makechap.py filename num" sys.exit(1) filename = sys.argv[1] num = int(sys.argv[2]) section = 0 subsection = 0 subsubsection = 0 nameindex = 0 name = "" # Regexs for

,...

sections h1 = re.compile(r".*?

[\d\.\s]*(.*?)

", re.IGNORECASE) h2 = re.compile(r".*?

[\d\.\s]*(.*?)

", re.IGNORECASE) h3 = re.compile(r".*?

[\d\.\s]*(.*?)

", re.IGNORECASE) h4 = re.compile(r".*?

[\d\.\s]*(.*?)

", re.IGNORECASE) data = open(filename).read() # Read data open(filename+".bak","w").write(data) # Make backup lines = data.splitlines() result = [ ] index = "\n\n" if subsection: index += "\n" index += """
  • %s\n""" % (nameindex,m.group(1)) subsection = 0 subsubsection = 0 skipspace = 1 continue m = h3.match(s) if m: nameindex += 1 subsection += 1 result.append("""

    %d.%d.%d %s

    """ % (nameindex,num,section, subsection, m.group(1))) if subsubsection: index += "\n" if subsection == 1: index += "\n" if section: index += "\n" index += "\n" data = "\n".join(result) data = data.replace("@INDEX@",index); # Write the file back out open(filename,"w").write(data) # Print the TOC data index = index.replace("#n","%s#n" % filename) print """

    %d %s

    \n""" % (filename,num,name) print index