0

我想从英语句子的解析描述(句法解析的压缩形式)生成解析树(Java 对象)。我也在使用 Java,也需要定义一个高效的树。例如。描述:

    (ROOT (S (NP (PRP I)) (VP (MD would) (VP (VB love) (S (VP (TO to) (VP (VB go) (PRT (RP out)) (PP (IN with) (NP (PRP you)))))))) (. .))
4

1 回答 1

0

我终于自己解决了:)

public static Node getParseTree(String[] parseTokens, ArrayList<Node> leafNodeList)
{
    Node top = new Node("TOP");
    Node rest = getParseTree(parseTokens, 2, top, false, leafNodeList);
    return top;
}

public static Node getParseTree(String[] parseTokens, int currIndex, Node lastNode, Boolean closeBrace, ArrayList<Node> leafNodeList)
{
    if(currIndex>=parseTokens.length) return lastNode;
    else if("(".equals(parseTokens[currIndex]))
    {
        Node newNode = lastNode.addChild(parseTokens[currIndex+1]);//The next token is the data for the new node constructed
        return getParseTree(parseTokens, currIndex+2, newNode, false, leafNodeList);
    }
    else if(")".equals(parseTokens[currIndex]))
    {
        if(closeBrace) return getParseTree(parseTokens, currIndex+1, lastNode.getParent(), true, leafNodeList);
        else return getParseTree(parseTokens, currIndex+1, lastNode, true, leafNodeList);
    }
    else //leaf node 
    {
        Node newNode = lastNode.addChild(parseTokens[currIndex]);
        leafNodeList.add(newNode);
        return getParseTree(parseTokens, currIndex+2, lastNode.getParent(), true, leafNodeList);
    }       
}

Node test(String parseDesc)
{
        parseDesc = parseDesc.replace("(", " ( ");
        parseDesc = parseDesc.replace(")", " ) ");
        String[] parseDescTokens = parseDesc.trim().split("\\s+");
        Node treeReqd = getParseTree(parseDescTokens, leafNodes);// Required Tree
}
于 2012-05-24T05:17:40.600 回答