2

Im using opennlp's Parse model to parse a line of input, my code:

public void parse(String input){
InputStream modelIn = null;
try {
    modelIn = new FileInputStream("en-parser-chunking.bin");
  ParserModel model = new ParserModel(modelIn);
    opennlp.tools.parser.Parser parser = ParserFactory.create(model);
    opennlp.tools.parser.Parse topParses[] = ParserTool.parseLine(input, parser, 1);
for (opennlp.tools.parser.Parse p : topParses){
            p.show();

                         }
}catch (IOException e) {
  e.printStackTrace();
}finally {
  if (modelIn != null) {
    try {
      modelIn.close();
    }
    catch (IOException e) {
    }
  }
}
    }

if my input is this is a test line p.show displays (TOP (S (NP (DT this)) (VP (VBZ is) (NP (DT a) (NN test) (NN line))))) but p.toString displays this is a test line

how can i make it the same as p.show?

4

2 回答 2

2

这对我有用...您必须使用重载的显示,它在内部更新传入的 StringBuffer 引用

public void parse(String input){
InputStream modelIn = null;
try {
    modelIn = new FileInputStream("en-parser-chunking.bin");
  ParserModel model = new ParserModel(modelIn);
    opennlp.tools.parser.Parser parser = ParserFactory.create(model);
    opennlp.tools.parser.Parse topParses[] = ParserTool.parseLine(input, parser, 1);
    for (opennlp.tools.parser.Parse p : topParses){

      StringBuilder sb = new StringBuilder(input.length() * 4);
      p.show(sb);
      //sb now contains all the tags
      System.out.println(sb);

    }
}catch (IOException e) {
  e.printStackTrace();
}finally {
  if (modelIn != null) {
    try {
      modelIn.close();
    }
    catch (IOException e) {
    }
  }
}
} 
于 2013-12-11T03:20:04.070 回答
0

正如 Greg 所报告的那样,这个问题的解决方案失败了。它失败了,因为该行读取错误:

StringBuilder sb = new StringBuilder(input.length() * 4);

在 OpenNLP 工具包中 Parse 类中的 show() 方法不能使用 StringBuilder 类型:

如果 StringBuilder 类型更改为 StringBuffer 类型,则发布的解决方案将起作用:

StringBuffer sb = new StringBuffer(input.length() * 4);

请参阅:https ://opennlp.apache.org/docs/1.9.0/apidocs/opennlp-tools/opennlp/tools/parser/Parse.html#show-java.lang.StringBuffer-

show(StringBuffer sb) 将指定的字符串缓冲区附加到此解析的字符串表示中。

于 2022-01-15T22:50:39.547 回答