简体   繁体   中英

Insert child node in nltk tree

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM