Created
December 20, 2009 20:40
-
-
Save sma/260626 to your computer and use it in GitHub Desktop.
parse a simple key-value data structure
This file contains hidden or 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
example = """ | |
start | |
{ | |
position1 "-1022.963745,793.409607,8.966581" | |
position2 "-1024.971558,70.542549,416.005066" | |
name "Start" | |
time 0.0 | |
active 1 | |
give | |
{ | |
item "flashlight" | |
weapon "rpg" | |
ammo | |
{ | |
amount 20 | |
type "rocket" | |
} | |
} | |
} | |
""" | |
def parse(itr): | |
kv = {} | |
for line in itr: | |
line = line.strip() | |
if " " in line: | |
key, value = line.split(" ", 1) | |
value = value.strip() | |
if value[0] == '"' and value[-1] == '"': kv[key] = value[1:-1] | |
else: kv[key] = float(value) if "." in value else int(value) | |
elif line == "{": | |
kv[name] = parse(itr) | |
elif line == "}": | |
break | |
elif line: | |
name = line | |
return kv | |
print parse(iter(example.splitlines())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment