简体   繁体   中英

Change value of leaf in NLTK

I want to change the value of a leaf in a parsed tree object in NLTK. I use the following code.

t = Tree(line)
chomsky_normal_form(t, horzMarkov=2, vertMarkov=1, childChar = "|", parentChar = "^")
print t

for leaf in t.leaves():
    if leaf==k[0][1]:
        leaf = "newValue"
 print t

As it is now the two 'print t' gives the exact same output of the tree. I thought it was possible to set a value to a leaf in this way but it seems I was wrong. How should I do to update the value of the leaf? The class of each leaf is str. So it is possible to change them but it doesn't seem update to update the object in the tree.

You could use treepositions('leaves') ( docs ) to get the position of the leaves in the tree and change it directly in your tree.

t = Tree(line)
chomsky_normal_form(t, horzMarkov=2, vertMarkov=1, childChar = "|", parentChar = "^")

for leafPos in t.treepositions('leaves'):
    if t[leafPos] == k[0][1]:
        t[leafPos] = "newValue"
 print t

I don't have previous experience with Tree, and the class documentation didn't suggest an obvious method for altering the leaves. But, looking at the source for the leaves method, it appears to just be a dressed-up form of list. I fiddled with it in the console for a minute, and I think this might get you moving in the right direction:

>>> t = Tree("(s (dp (d the) (np dog)) (vp (v chased) (dp (d the) (np cat))))")
>>> t.leaves()
['the', 'dog', 'chased', 'the', 'cat']
>>> t[0][0][0] = "newValue"
>>> t.leaves()
['newValue', 'dog', 'chased', 'the', 'cat']

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