Reputation: 4473
Assuming that I can read and edit all tree's leaves labels, using the following code:
for leaf in t.treepositions('leaves'):
t[leaf] = new_value
How could I add a new leaf as a child of the actual leaf t[leaf]? Could be a silly question, but I haven't lot of experience with nltk.
Upvotes: 2
Views: 1458
Reputation: 1281
Are you bound to using the treepositions method? If not; if you just loop through all subtrees of your tree (recursively if needed), you can insert something at any point (an nltk tree is actually 'just' a list representation).
Here's an example that addes a modifier to a VP (for no apparant reason :)):
import nltk
t = nltk.tree.Tree.fromstring("(S (NP I) (VP (V saw) (NP him)))")
print(t)
for index, st in enumerate(t.subtrees()):
if st.label() == 'VP':
st.insert(index, nltk.tree.Tree('ADV', ['yesterday']))
print(t)
Output:
(S (NP I) (VP (V saw) (NP him)))
(S (NP I) (VP (V saw) (NP him) (ADV yesterday)))
Hope this helps.
Upvotes: 3