Jon*_*han 2 python subtree nltk
我需要 NLTK 树的一些帮助。
我试图从这棵法国树中提取一些子树:

(SENT (NP-SUJ? (PRO=H Personne)) (VN=H (ADV* ne) (V=H sait)) (ADV* exactement) (PONCT* .))
Run Code Online (Sandbox Code Playgroud)
我只想提取 POS 标签末尾带有 '=H' 的树,然后添加父节点:
像这样: (NP-SUJ? (PRO=H Personne)) and this: (VN=H (V=H sait))
我写了一个函数来这样做:
def AddParent(tree):
grammar = []
for subtree in tree.subtrees():
if subtree.height()==2 and subtree.label().endswith("=H"):
PartialTree = ParentedTree(subtree.parent().label(),
[ParentedTree(subtree.label(), subtree)])
grammar.append(PartialTree)
return grammar
#Test
pt = ParentedTree.fromstring("(SENT (NP-SUJ? (PRO=H Personne)) (VN=H (ADV* ne) (V=H sait)) (ADV* exactement) (PONCT* .))")
AddParent(pt)
[ParentedTree('NP-SUJ?', [ParentedTree('PRO=H', ['Personne'])]),
ParentedTree('VN=H', [ParentedTree('V=H', ['sait'])])]
Run Code Online (Sandbox Code Playgroud)
我在这里有两个问题:首先,我想继续向原始树中的那些子树添加信息。例如,我想继续添加祖先节点,然后添加子节点,以执行以下操作:
(SENT (NP-SUJ? ) (VN=H (V=H sait)))
Run Code Online (Sandbox Code Playgroud)

但我失去了原始树的踪迹......
其次,该parent()函数返回其中包含的所有子树。我只想拥有特定的节点。
提取最后一个子树的好方法是什么???
非常感谢您的帮助!我是新手,但我真的很喜欢它!
我不能说我理解你的抱怨parent()(也许你的意思是subtrees()?),但有更简单的方法来获得子树:
表面改进:该subtrees()函数接受一个filter参数,因此您不必检查代码中返回的子树:
for subtree in tree.subtrees(filter=lambda t: t.label().endswith("=H"))
Run Code Online (Sandbox Code Playgroud)子树是对原始树的子部分的引用。如果你不修改它,它仍然是原始树的一部分,你可以提升树(因为你使用了“parented”树。)事实上,注意如果你对子树的内容进行修改,原始树将被修改。 但是不是将您找到的树嵌入到新节点下,而是构建一个全新的副本:
partial = ParentedTree(subtree.parent().label(), [ subtree.copy() ])
Run Code Online (Sandbox Code Playgroud)
然后您可以自由删除或更改副本中的分支,并且您仍然拥有原始tree和subtree可以使用的分支。
虽然您可以使用该parent()方法爬上树,但我经常发现使用“树位置”更方便。树的位置是一个整数元组,它充当树的路径(使用它就像列表上的整数索引)。要找到父级,您只需要切掉 treeposition 的最后一个元素:
for postn in tree.treepositions():
if tree[postn].label().endswith("=H"):
parentpos = postn[:-1] # everything but the last element
partial = Tree(tree[parentpos].label(), [ tree[postn] ])
Run Code Online (Sandbox Code Playgroud)
请注意,如果您使用此方法,则不再需要该parent()方法,因此您最好使用Tree,而不是ParentedTree。
上面的内容可能并没有完全按照您的要求做(很难看出您在做什么),但我希望您能了解情况。
| 归档时间: |
|
| 查看次数: |
5519 次 |
| 最近记录: |