How can I integrate stanford parserra software into my java program?

I need to develop a project in Java that uses the Stanford analyzer to separate sentences and needs to generate a graph that shows the relationship between the words in the sentence. For example: Ohio is located in America. Exit:

output

image shows a graph. But the output should not be like that, but it should show the connection between the words in the form of a graph. A graph can be generated using Jgraph, Jung. But first, I need to integrate the parser software into my program. So how can I integrate the parser?

+4
source share
1 answer
  • Stanford Parser:
  • jars ( ).
  • , : ( , )

    import java.io.StringReader;
    import java.util.List;
    
    import edu.stanford.nlp.ling.CoreLabel;
    import edu.stanford.nlp.process.TokenizerFactory;
    import edu.stanford.nlp.parser.lexparser.LexicalizedParser;
    import edu.stanford.nlp.process.CoreLabelTokenFactory;
    import edu.stanford.nlp.process.PTBTokenizer;
    import edu.stanford.nlp.process.Tokenizer;
    import edu.stanford.nlp.trees.Tree;
    
    class Parser {
    
        private final static String PCG_MODEL = "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz";        
    
        private final TokenizerFactory<CoreLabel> tokenizerFactory = PTBTokenizer.factory(new CoreLabelTokenFactory(), "invertible=true");
    
        private final LexicalizedParser parser = LexicalizedParser.loadModel(PCG_MODEL);
    
        public Tree parse(String str) {                
            List<CoreLabel> tokens = tokenize(str);
            Tree tree = parser.apply(tokens);
            return tree;
        }
    
        private List<CoreLabel> tokenize(String str) {
            Tokenizer<CoreLabel> tokenizer =
                tokenizerFactory.getTokenizer(
                    new StringReader(str));    
            return tokenizer.tokenize();
        }
    
        public static void main(String[] args) { 
            String str = "My dog also likes eating sausage.";
            Parser parser = new Parser(); 
            Tree tree = parser.parse(str);  
    
            List<Tree> leaves = tree.getLeaves();
            // Print words and Pos Tags
            for (Tree leaf : leaves) { 
                Tree parent = leaf.parent(tree);
                System.out.print(leaf.label().value() + "-" + parent.label().value() + " ");
            }
            System.out.println();               
        }
    }
    
+13

All Articles