在NLTK中更改叶子的值

时间:2013-05-02 19:17:43

标签: python tree nlp nltk

我想在NLTK中更改已解析树对象中叶子的值。我使用以下代码。

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

现在,两个'print t'给出了树的完全相同的输出。我认为有可能以这种方式为叶子设置一个值,但似乎我错了。 我该怎么做才能更新叶子的价值? 每片叶子的类是str。因此可以更改它们,但似乎不更新以更新树中的对象。

2 个答案:

答案 0 :(得分:2)

您可以使用treepositions('leaves')docs)获取树中树叶的位置,并直接在树中更改。

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

答案 1 :(得分:1)

我之前没有使用Tree的经验,而且类文档没有提出改变叶子的明显方法。但是,查看叶子方法的source,它似乎只是一个打扮的列表形式。我在控制台里摆弄了一分钟,我认为这可能会让你朝着正确的方向前进:

>>> 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']
相关问题