Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Need help to tree-ify nested parenthesis...

Thread Tools

Need help to tree-ify nested parenthesis...

Gregory Nans
Posts: n/a

i need some help to 'tree-ify' a string...

for example i have strings such as :

s = """A(here 's , B(A ) silly test) C(to show D(what kind) of stuff i

and i need to parse them to have a tree representation such as :

["A", [
"here 's" ,
[ "B", [
'A ) "silly test'
["C", [
"to show",
["D", [
"what kind"
"of stuff i need",

notes : "ALLCAPS(something else)" are some kind of tag, "something
else" may contain ALLCAPS() and thus be nested or contain others
characters. the parenthesis between 'A' and 'silly test' isn't a
mistake but a case to handle string is quite well formed = orphan
parenthesis will always be surrounded by whitespace - like in 'A )
silly test' or 'A ( silly test'

if have started to write a function which give me pos and nested
string, but still need help to finish to tree-ify it from there... or
maybe there is a more obvious way ? (i think i didn't need to create
real finite state automata for this stuff)


>>> parse(d)

-1 D what kind 42 @ 51
-1 C to show D(what kind) of stuff i need 32 @ 68
-1 B A ) silly test 14 @ 28
-1 A here 's , B(A ) silly test) C(to show D(what kind) of stuff i
need) 2 @ 69


def parse(s):

n = len(s)

p = re.compile(r'([A-Z_]+\()')
pos = []
iterator = p.finditer(s)
for match in iterator:

j = 0
for (start, end) in pos:
opened = 0
i = end
while i < n - j:
if s[i] == '(':
opened += 1
if s[i] == ')' and s[i - 1] != ' ':
opened -= 1
if opened < 0:
print opened, s[start:end-1], s[end:i], "%s @ %s" % (end,
i += 1

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
dealing with nested xml within nested xml within...... Ultrus Python 3 07-09-2007 09:00 PM
Is nested class automatically friend of class that it is nested in? C++ 5 09-25-2006 08:31 AM
Nested Vector Nester Classes are Nested in my Brain Chad E. Dollins C++ 3 11-08-2005 04:46 AM
Need help for optimising nested ifs-help me plz panic situation!!! s.subbarayan C Programming 3 09-11-2004 03:23 PM
Nested iterators (well, not nested exactly...) Russ Perry Jr Java 2 08-20-2004 06:51 PM