我是 nlp 的新手,我正在尝试使用斯坦福解析器从文本中提取 (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();
他们返回的是标签
最佳答案
你可以得到子树 tr 下的单词列表
tr.yield()
您可以使用 Sentence 中的便捷方法将其转换为字符串形式:
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()));
}
关于java - 从输出解析树中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12514621/