Skip to content

Instantly share code, notes, and snippets.

@mimoo
Created December 5, 2020 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mimoo/60f35cf79593171d114247403671307e to your computer and use it in GitHub Desktop.
Save mimoo/60f35cf79593171d114247403671307e to your computer and use it in GitHub Desktop.
script to print out sections of `.adoc` files, assuming they all start with `1_something.adoc`, `2_something_else.adoc`, etc.
import glob
import re
import os
def count_equal(line):
res = 0
for i in range(10):
if line[i] == "=":
res += 1
else:
break
return res
def parse_chapter(chapt_num, chapter):
section_depth = {0: chapt_num}
# read section of the chapter
first_line = True
is_comment = False
is_formula = False
for line in chapter:
# skip first line
if first_line:
first_line = False
continue
# skip comments
if is_comment:
if line[:4] == "////":
is_comment = False
else:
continue
else:
if line[:4] == "////":
is_comment = True
continue
# skip formulas
if is_formula:
if line[:4] == "****":
is_formula = False
else:
continue
else:
if line[:4] == "****":
is_formula = True
continue
# retrieve information from titles only (e.g. ==== TITLE)
depth = count_equal(line)
if depth > 0:
name = line.rsplit("=", 1)[1].rstrip("\n")
if name == "":
continue
# print("section detected", line, name)
section_depth = print_section_number(section_depth, depth-1, name)
def print_section_number(section_depth, depth, name):
# print("add", depth, section_depth)
# add in dictionary
if depth in section_depth:
section_depth[depth] += 1
else:
section_depth[depth] = 1
section_depth = clear_depth(section_depth, depth)
# format
fmt = ""
# print("debug", depth-1, section_depth)
for i in range(depth+1):
# print("access", i)
fmt += str(section_depth[i]) + "."
print("-" * depth + fmt + name)
return section_depth
def clear_depth(section_depth, depth):
while True:
depth += 1
if depth in section_depth:
section_depth[depth] = 0
else:
break
return section_depth
def main():
# read chapter files sorted by their number
filenames = glob.glob("./manuscript/*_*.adoc")
filenames = sorted(filenames, key=lambda line: int(os.path.basename(line).split("_", 1)[0]))
for filename in filenames:
with open(filename, 'r') as f:
name = os.path.basename(filename)
print(name)
chapt_num = int(name.split("_", 1)[0])
parse_chapter(chapt_num-1, f)
if __name__=="__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment