斯坦福依赖性解析器 - 如何获得跨度?

时间:2013-04-16 00:36:41

标签: java parsing nlp stanford-nlp

我正在使用Java中的Stanford库进行依赖解析。 有没有办法在我的原始依赖字符串中找回索引? 我试图调用getSpans()方法,但它为每个标记返回null:

LexicalizedParser lp = LexicalizedParser.loadModel(
        "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz",
        "-maxLength", "80", "-retainTmpSubcategories");
TreebankLanguagePack tlp = new PennTreebankLanguagePack();
GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
Tree parse = lp.apply(text);
GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
Collection<TypedDependency> tdl = gs.typedDependenciesCollapsedTree();
for(TypedDependency td:tdl)
{
      td.gov().getSpan()  // it's null!
      td.dep().getSpan()  // it's null!
}

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

我终于编写了自己的辅助函数来缩小原始字符串的范围:

public HashMap<Integer, TokenSpan> getTokenSpans(String text, Tree parse)
{
    List<String> tokens = new ArrayList<String>();
    traverse(tokens, parse, parse.getChildrenAsList());
    return extractTokenSpans(text, tokens);
}

private void traverse(List<String> tokens, Tree parse, List<Tree> children)
{
    if(children == null)
        return;
    for(Tree child:children)
    {
        if(child.isLeaf())
        {
            tokens.add(child.value());
        }
        traverse(tokens, parse, child.getChildrenAsList());         
    }
}

private HashMap<Integer, TokenSpan> extractTokenSpans(String text, List<String> tokens)
{
    HashMap<Integer, TokenSpan> result = new HashMap<Integer, TokenSpan>();
    int spanStart, spanEnd;

    int actCharIndex = 0;
    int actTokenIndex = 0;
    char actChar;
    while(actCharIndex < text.length())
    {
        actChar = text.charAt(actCharIndex);
        if(actChar == ' ')
        {
            actCharIndex++;
        }
        else
        {
            spanStart = actCharIndex;
            String actToken = tokens.get(actTokenIndex);
            int tokenCharIndex = 0;
            while(tokenCharIndex < actToken.length() && text.charAt(actCharIndex) == actToken.charAt(tokenCharIndex))
            {
                tokenCharIndex++;
                actCharIndex++;
            }

            if(tokenCharIndex != actToken.length())
            {
                //TODO: throw exception
            }
            actTokenIndex++;
            spanEnd = actCharIndex;
            result.put(actTokenIndex, new TokenSpan(spanStart, spanEnd));
        }
    }
    return result;
}

然后我会打电话给

 getTokenSpans(originalString, parse)

所以我得到一张地图,它可以将每个标记映射到相应的标记范围。 这不是一个优雅的解决方案,但至少它可行。

答案 1 :(得分:0)

即使你已经回答了自己的问题,这也是一个老问题:我今天偶然发现了同样的问题,但是使用了(斯坦福)LexicalizedParser而不是Dependency Parser。 Haven没有测试它的依赖关系1,但以下解决了我在lexParser场景中的问题:

List<Word> wl = tree.yieldWords();
int begin = wl.get(0).beginPosition();
int end = wl.get(wl.size()-1).endPosition();
Span sp = new Span(begin, end);

其中Span保存(子)树的索引。 (如果你一直走到终端,我想同样应该在令牌级别上工作)。

希望这有助于其他人遇到同样的问题!