假設我有一個包含nltk樹類的樹的變量。是否有任何像parent()或返回節點的父節點的函數?在nltk樹中,如何從小孩訪問父母?
2
A
回答
4
使用NLTK 3,您可以使用nltk.tree.ParentedTree 它有一個parent()方法。
3
您需要不同的數據結構:一個樹,其節點包含指向其父級的指針。 NLTK現在提供類型nltk.tree.ParentedTree
(正如@Gerhard已經指出的那樣)。但NLTK語料庫和工具會生成簡單的Tree
對象,因此您需要轉換。如果您擁有一個包含樹可變mytree
,將其轉換是這樣的:
from nltk.tree import ParentedTree
newtree = ParentedTree.convert(mytree)
新樹的節點將有一個parent()
方法,你可以用它來瀏覽了樹。