我想簡化我的分析樹的節點,即給出一個節點,我擺脫了第一個連字符以及連字符之後的任何內容。例如,如果一個節點是NP-TMP-FG,我想使它成爲NP,如果它是SBAR-SBJ,我想使它成爲SBAR等等。這是我有一個解析樹的例子如何遍歷樹的所有節點?
((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)))) (. .)))
這是我的代碼,但它不起作用。
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
編輯:
我想這個問題是subtree.label()顯示的節點,但它不能被改變,因爲它是一個函數。打印subtree.label的輸出()是:
S
S-TPC-2
NP-SBJ
NP
DT
NN
,
等等...