Skip to content

Instantly share code, notes, and snippets.

@hoffmanc
Created April 8, 2011 11:29
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 hoffmanc/909666 to your computer and use it in GitHub Desktop.
Save hoffmanc/909666 to your computer and use it in GitHub Desktop.
outline2array.py
import re
import json
def get_lvl(line):
return len(re.findall("\t",line))
def get_tree(f):
global i
outline = []
while i < len(f):
lvl = get_lvl(f[i])
key = f[i].strip()
node = { 'lvl': lvl, 'key': key, 'i': i }
next_lvl = i + 1 < len(f) and get_lvl(f[i+1])
if outline and outline[0]['lvl'] > lvl:
break
else:
i+=1
if next_lvl > lvl:
node['kids'] = get_tree(f)
outline.append(node)
if next_lvl < lvl:
break
return outline
def main():
f = open("../categories.txt","r").readlines()
fo = open("categories.pydump","w")
global i
i = 0
tree = get_tree(f)
json.dump(tree, fo)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment