Skip to content

Instantly share code, notes, and snippets.

@jittat
Created August 21, 2017 23:19
Show Gist options
  • Save jittat/8566065e464356ef5865597aa777e323 to your computer and use it in GitHub Desktop.
Save jittat/8566065e464356ef5865597aa777e323 to your computer and use it in GitHub Desktop.
def extract_line(line):
"""
>>> extract_line("* hello world")
('hello world', 1)
>>> extract_line("** this is a ** test!!")
('this is a ** test!!', 2)
"""
depth = 0
l = len(line)
while (depth < l) and (line[depth] == '*'):
depth += 1
return (line[depth+1:], depth)
def parse_header(header):
"""
>>> parse_header("* a\\n* b\\n* c")
[['a', []], ['b', []], ['c', []]]
>>> parse_header("* a\\n** b\\n* c")
[['a', [['b', []]]], ['c', []]]
>>> parse_header("* a\\n** b\\n** c\\n*** d\\n* e")
[['a', [['b', []], ['c', [['d', []]]]]], ['e', []]]
"""
nodes = []
current_nodes = []
for line in header.split("\n"):
title,depth = extract_line(line)
this_node = [title,[]]
if depth == 1:
nodes.append(this_node)
current_nodes = [this_node]
else:
current_nodes[depth-2][1].append(this_node)
current_nodes = current_nodes[:depth-1]
current_nodes.append(this_node)
return nodes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment