Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

Extract parent and child node from python tree

I am using nltk's Tree data structure.Below is the sample nltk.Tree.

(S
  (S
    (ADVP (RB recently))
    (NP (NN someone))
    (VP
      (VBD mentioned)
      (NP (DT the) (NN word) (NN malaria))
      (PP (TO to) (NP (PRP me)))))
  (, ,)
  (CC and)
  (IN so)
  (S
    (NP
      (NP (CD one) (JJ whole) (NN flood))
      (PP (IN of) (NP (NNS memories))))
    (VP (VBD came) (S (VP (VBG pouring) (ADVP (RB back))))))
  (. .))

I am not aware of nltk.Tree datastructure. I want to extract the parent and the super parent node for every leaf node e.g. for 'recently' I want (ADVP, RB), and for 'someone' it is (NP, NN)This is the final outcome i want.Earlier answer used eval() function to do so which i want to avoid.

[('ADVP', 'RB'), ('NP', 'NN'), ('VP', 'VBD'), ('NP', 'DT'), ('NP', 'NN'), ('NP', 'NN'), ('PP', 'TO'), ('NP', 'PRP'), ('S', 'CC'), ('S', 'IN'), ('NP', 'CD'), ('NP', 'JJ'), ('NP', 'NN'), ('PP', 'IN'), ('NP', 'NNS'), ('VP', 'VBD'), ('VP', 'VBG'), ('ADVP', 'RB')]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Python code for the same without using eval function and using nltk tree datastructure

sentences = " (S
  (S
(ADVP (RB recently))
(NP (NN someone))
(VP
  (VBD mentioned)
  (NP (DT the) (NN word) (NN malaria))
  (PP (TO to) (NP (PRP me)))))
  (, ,)
  (CC and)
  (IN so)
  (S
    (NP
      (NP (CD one) (JJ whole) (NN flood))
      (PP (IN of) (NP (NNS memories))))
    (VP (VBD came) (S (VP (VBG pouring) (ADVP (RB back))))))
  (. .))"

print list(tails(sentences))


def tails(items, path=()):
for child in items:
    if type(child) is nltk.Tree:
        if child.label() in {".", ","}:  # ignore punctuation
            continue
        for result in tails(child, path + (child.label(),)):
            yield result
    else:
        yield path[-2:]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...