不,NLTK中没有任何内置函数来返回特定深度的树。
How to Traverse an NLTK Tree object?
为了提高效率,您可以先迭代深度,并且仅当深度小于必要值时才重复,例如。
import nltk
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]
pattern = """NP: {<DT>?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(sentence)
def traverse_tree(tree, depth=float('inf')):
"""
Traversing the Tree depth-first,
yield leaves up to `depth` level.
"""
for subtree in tree:
if type(subtree) == nltk.tree.Tree:
if subtree.height() <= depth:
yield subtree.leaves()
traverse_tree(subtree)
list(traverse_tree(result, 2))
[[('the', 'DT'), ('little', 'JJ'), ('yellow', 'JJ'), ('dog', 'NN')],
[('barked', 'VBD')],
[('at', 'IN')],
[('the', 'DT'), ('cat', 'NN')]]
另一个例子:
x = """(S
(NP the/DT
(AP little/JJ yellow/JJ)
dog/NN)
(VBD barked/VBD)
(IN at/IN)
(NP the/DT cat/NN))"""
list(traverse_tree(Tree.fromstring(x), 2))
[输出]:
[['barked/VBD'], ['at/IN'], ['the/DT', 'cat/NN']]