有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将子节点添加到Stanford树

我正在尝试向stanford parsetree添加一个新节点,尽管我目前尝试的方法不起作用:

因此,我使用TregexMatcher并返回一棵树,如:

(VP 
    (VB run) 
    (PP 
        (To to) 
        (NP 
            (DT the) 
            (NN shop) 
        ) 
    )
)

我试图插入(VBD did)作为(VP)的第一个子项,并给出树:

(VP 
    (VBD did)
    (VB run) 
    (PP 
        (To to) 
        (NP 
            (DT the) 
            (NN shop) 
        ) 
    )
)

以下是我尝试过的代码:

private Tree addNode(Tree tree, Label posTag, Label value, int index) {

    SimpleTree posNode = new SimpleTree(posTag);
    posNode.setValue(posTag.value());

    SimpleTree valueNode = new SimpleTree(value);
    valueNode.setValue(value.value());

    posNode.addChild(valueNode);

    tree.insertDtr(posNode, index);
    return tree;
}

我一直在使用online documentation,尽管我不确定如何处理这个问题

我哪里做错了?有没有人可以把我链接到网上的例子

编辑:以上代码后修改的树为:

(VP
    ( ) 
    (VB run)
    (PP 
        (TO to)
        (NP 
            (DT the) 
            (NN shop)
        )
    )
)

共 (1) 个答案

  1. # 1 楼答案

    错误是使用了SimpleTree。一个SimpleTree只是一个没有节点标签的树结构,因此用处不大。我在文档中添加了一条注释,说明了这一点。使用LabeledScoredTreeNode它可以很好地工作:

    private static Tree addNodeFixed(Tree tree, Label posTag, Label value, int index) {
      Tree posNode = new LabeledScoredTreeNode(posTag);
      posNode.setValue(posTag.value());
      Tree valueNode = new LabeledScoredTreeNode(value);
      valueNode.setValue(value.value());
      posNode.addChild(valueNode);
    
      tree.insertDtr(posNode, index);
      return tree;
    }
    

    然而,如果您使用Tregex来匹配树,您可能会发现使用Tsurgeon更容易。不过,请注意插入上的无限循环

    private static Tree addNodeTsurgeon(Tree tree, String tag, String word) {
      TregexPattern pat = TregexPattern.compile("__=root !> __ !< " + tag);
      TsurgeonPattern surgery = Tsurgeon.parseOperation(
              "insert (" + tag + " " + word +") >1 root");
      return Tsurgeon.processPattern(pat, surgery, tree);
    }