How to iterate through all nodes of a tree?

*爱你&永不变心* 提交于 2020-02-07 11:37:16

问题


I want to simplify my parse trees' nodes, i.e. given a node I get rid of the first hyphen and whatever that comes after that hyphen. For example if a node is NP-TMP-FG, I want to make it NP and if it is SBAR-SBJ, I want to make it SBAR and so on. This is an example of one parse tree that I have

( (S (S-TPC-2 (NP-SBJ (NP (DT The) (NN asbestos) (NN fiber) ) (, ,)
(NP (NN crocidolite) ) (, ,) ) (VP (VBZ is) (ADJP-PRD (RB unusually) (JJ resilient) )
(SBAR-TMP (IN once) (S (NP-SBJ (PRP it) ) (VP (VBZ enters) (NP (DT the) (NNS lungs) ))))
(, ,) (PP (IN with)(S-NOM (NP-SBJ (NP (RB even) (JJ brief) (NNS exposures) ) (PP (TO to)
(NP (PRP it) ))) (VP (VBG causing) (NP (NP (NNS symptoms) ) (SBAR (WHNP-1 (WDT that) )
(S (NP-SBJ (-NONE- *T*-1) ) (VP (VBP show) (PRT (RP up) ) (ADVP-TMP (NP (NNS decades) ) 
(JJ later) )))))))))) (, ,) (NP-SBJ (NNS researchers) ) (VP (VBD said)(SBAR (-NONE- 0) 
(S (-NONE- *T*-2) )))    (. .) )) 

This is my code but it doesn't work.

import re
import nltk
from nltk.tree import *
tree = Tree.fromstring(line) // Each parse tree is stored in one single line
for subtree in tree.subtrees():
    re.sub('-.*', '', subtree.label())
print tree

Edit:

I guess the problem is that subtree.label() shows the nodes but it cannot be changed since it is a function. The output of print subtree.label() is :

S
S-TPC-2
NP-SBJ
NP
DT
NN
,

and so on...


回答1:


You can do something like that:

for subtree in tree.subtrees():
    first = subtree.label().split('-')[0]
    subtree.set_label(first)



回答2:


I came up with this:

for subtree in tree.subtrees():
    s = subtree.label()
    subtree.set_label(re.sub('-.*', "", s))


来源:https://stackoverflow.com/questions/27052690/how-to-iterate-through-all-nodes-of-a-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!