从输出解析树中提取文本

时间:2012-09-20 14:18:11

标签: java nlp stanford-nlp

我是nlp的新手,我正在尝试使用stanford解析器从文本中提取(NP)句子,我想检索文本中标记的部分(NP)

如果一个部件被标记(NP)并且其中的一个较小的部分也被标记(NP)我想占用较小的部分。

到目前为止,我设法按照以下方法做了我想做的事情:

private static ArrayList<Tree> extract(Tree t) 
{
    ArrayList<Tree> wanted = new ArrayList<Tree>();
   if (t.label().value().equals("NP") )
    {
       wanted.add(t);
        for (Tree child : t.children())
        {
            ArrayList<Tree> temp = new ArrayList<Tree>();
            temp=extract(child);
            if(temp.size()>0)
            {
                int o=-1;
                o=wanted.indexOf(t);
                if(o!=-1)
                    wanted.remove(o);
            }
            wanted.addAll(temp);
        }
    }

    else
        for (Tree child : t.children())
            wanted.addAll(extract(child));
    return wanted;
}

此方法的返回类型是树的列表,当我执行以下操作时:

     LexicalizedParser parser = LexicalizedParser.loadModel();
        x = parser.apply("Who owns club barcelona?");
     outs=extract(x);
    for(int i=0;i<outs.size();i++){System.out.println("tree #"+i+": "+outs.get(i));}

是:

tree #0: (NP (NN club) (NN barcelona))

我希望输出立即为"club barcelona",没有标记,我尝试.labels();属性,.label().value();他们返回标记

1 个答案:

答案 0 :(得分:10)

您可以使用

获取子树tr下的单词列表
tr.yield()

您可以使用句子中的便捷方法将其转换为String表单:

Sentence.listToString(tr.yield())

你可以在你正在做的时候走一棵树,但是如果你要做很多这样的事情,你可能想看一下tregex,它可以通过声明模式更容易地找到树中的特定节点,例如NP以下没有NP。一个简洁的方法来做你正在寻找的是:

Tree x = lp.apply("Christopher Manning owns club barcelona?");
TregexPattern NPpattern = TregexPattern.compile("@NP !<< @NP");
TregexMatcher matcher = NPpattern.matcher(x);
while (matcher.findNextMatchingNode()) {
  Tree match = matcher.getMatch();
  System.out.println(Sentence.listToString(match.yield()));
}
相关问题