簡體   English   中英

在NLTK中交換樹的葉子標簽

[英]Swap leaf label of Tree in NLTK

我已經使用NLTK的RegexpParser解析了這個帶標簽的句子: 狗追了黑貓 ,我使用了以下grammar

tagged_ = [('the', 'DT'), ('dog', 'NN'), ('chased', 'VBD'), ('the', 'DT'), ('black', 'JJ'), ('cat', 'NN')]

grammar = """NP: {<DT>?<JJ>*<NN>} VP: {<MD>?<VBD>}""" cp = nltk.RegexpParser(grammar) result = cp.parse(tagged_) print(result) result.draw()

這是print(result)result.draw()

(S (NP the/DT dog/NN) (VP chased/VBD) (NP the/DT black/JJ cat/NN)) 樹

現在我想重新排序其中(VP chased/VBD)(NP the/DT dog/NN)交換的葉子,如下所示:

S (VP chased/VBD) (NP the/DT dog/NN) (NP the/DT black/JJ cat/NN))然后顯示['chased','the','dog','the','black','cat'] 有什么辦法嗎?

您可以將nltk.Tree對象視為兩個值的元組。 第一個值是根節點的名稱,第二個值是包含子樹或葉子的列表。 您可以通過在根列表中追加子樹來構建復雜的樹:

>>> from nltk import Tree
>>> tree = Tree('S', [])
>>> np = Tree('NP', ['The', 'dog'])
>>> tree.append(np)
>>> vp = Tree('VP', ['barks'])
>>> tree.append(vp)
>>> print tree
(S (NP the dog) (VP barks))

您可以通過tree.subtrees()遍歷所有子樹:

>>> for sub in tree.subtrees():
...     print sub
(S (NP the dog) (VP barks) 
(NP the dog)
(VP barks)

您如何看到該方法輸出所有子樹,即在復雜樹中獲得子樹,子子樹,子子子樹...因此,在您的情況下,您最好通過第一棵樹級別的切片來獲得訪問權限:

>>> new = Tree('S', [])
>>> for i in xrange(len(tree)):
...     if tree[i].label() == 'VP':
...         new.insert(0, tree[i])
...     else:
...         new.append(tree[i])

>>> print new
(S (VP barks) (NP the dog))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM