编程语言
首页 > 编程语言> > java – Stanford Dependency Parser – 如何获得跨度?

java – Stanford Dependency Parser – 如何获得跨度?

作者:互联网

我正在使用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!
}

任何的想法?

解决方法:

我终于编写了自己的帮助函数,以获得原始字符串的跨度:

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)

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

标签:java,parsing,nlp,stanford-nlp
来源: https://codeday.me/bug/20190703/1370289.html