NLTK中叶的变化值

2024-10-08 18:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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,所以可以更改它们,但是更新树中的对象似乎没有更新。在


Tags: 对象代码formtreeforlineprintnormal
2条回答

我以前没有使用Tree的经验,而且类文档也没有建议一个明显的方法来改变叶子。但是,看看leaves方法的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']

您可以使用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

相关问题 更多 >

    热门问题