Created
April 22, 2015 12:55
-
-
Save constructor-igor/5f881c32403e3f313e6f to your computer and use it in GitHub Desktop.
parsing nested parentheses in python, grab content by level
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
#http://stackoverflow.com/questions/4284991/parsing-nested-parentheses-in-python-grab-content-by-level | |
def parenthetic_contents(string): | |
"""Generate parenthesized contents in string as pairs (level, contents).""" | |
stack = [] | |
for i, c in enumerate(string): | |
if c == '(': | |
stack.append(i) | |
elif c == ')' and stack: | |
start = stack.pop() | |
yield (len(stack), string[start + 1: i]) | |
>>> list(parenthetic_contents('(a(b(c)(d)e)(f)g)')) | |
[(2, 'c'), (2, 'd'), (1, 'b(c)(d)e'), (1, 'f'), (0, 'a(b(c)(d)e)(f)g')] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment