javaparsingstanford-nlpopennlp

Cannot convert result of opennlp Parse


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?


Solution

  • this works for me... you have to use the overloaded show, which internally updates the StringBuffer reference passed in

    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) {
        }
      }
    }
    }