Created
April 8, 2011 11:29
-
-
Save hoffmanc/909666 to your computer and use it in GitHub Desktop.
outline2array.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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