我正在使用nltk的树数据结构。下面是示例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))))))
(. .))
我不知道nltk.Tree数据结构。我想为每个叶节点提取父节点和超级父节点,例如最近'我想(ADVP,RB),以及某人'它是(NP,NN)这是我想要的最终结果。较早的答案使用了eval()函数来做到这一点,我想避免。
[('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')]
答案 0 :(得分:0)
不使用eval函数和使用nltk树数据结构的Python代码
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:]