python - library for transforming a node tree -



python - library for transforming a node tree -

i'd able express general transformation of 1 tree without writing bunch of repetitive spaghetti code. there libraries help problem? target language python, i'll @ other languages long it's feasible port python.

example: i'd transform node tree: (please excuse s-expressions)

(a (b) (c) (d))

into one:

(c (b) (d))

as long parent , sec ancestor c, regardless of context (there may more parents or ancestors). i'd express transformation in simple, concise, , re-usable way. of course of study illustration specific. please seek address general case.

edit: refactoringng kind of thing i'm looking for, although introduces exclusively new grammar solve problem, i'd avoid. i'm still looking more and/or improve examples.

background:

i'm able convert python , cheetah (don't ask!) files tokenized tree representations, , in turn convert lxml trees. plan re-organize tree , write-out results in order implement automated refactoring. xslt seems standard tool rewrite xml, syntax terrible (in opinion, obviously) , nobody @ our shop understand it.

i write functions utilize lxml methods (.xpath , such) implement refactorings, i'm worried wind bunch of purpose-built spaghetti code can't re-used.

let's seek in python code. i've used strings leaves, work objects.

def lift_middle_child(in_tree): (a, (b,), (c,), (d,)) = in_tree homecoming (c, (b,), (d,)) print lift_middle_child(('a', ('b',), ('c',), ('d',))) # utilize lists

this sort of tree transformation improve performed in functional style - if create bunch of these functions, can explicitly compose them, or create composition function work them in point-free style.

because you've used s-expressions, assume you're comfortable representing trees nested lists (or equivalent - unless i'm mistaken, lxml nodes iterable in way). obviously, illustration relies on known input structure, question implies that. can write more flexible functions, , still compose them, long have uniform interface.

here's code in action: http://ideone.com/02uv0i

now, here's function reverse children, , using , above function, 1 lift , reverse:

def compose2(a,b): # might want functional library homecoming lambda *x: a(b(*x)) def compose(*funcs): #compose(a,b,c) = a(b(c(x))) - might want reverse homecoming reduce(compose2,funcs) def reverse_children(in_tree): homecoming in_tree[0:1] + in_tree[1:][::-1] # cryptic, works subscriptable lift_and_reverse = compose(reverse_children,lift_middle_child) # right function applied first - if find confusing, reverse order in compose function. print lift_and_reverse(('a', ('b',), ('c',), ('d',)))

python refactoring tree expression-trees nodes

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -