我必须在 java 中开发一个项目,该项目使用斯坦福解析器来分隔句子,并且必须生成一个图表来显示句子中单词之间的关系。例如:俄亥俄州位于美国。输出:
图像显示了图表。但输出不必相同,但必须以图形形式显示单词之间的关系。该图可以使用 Jgraph, Jung 生成。但最初我必须将解析器软件集成到我的程序中。那么如何集成解析器?
使用以下代码片段解析句子并返回选区树:(可以通过检查树的结构来构建依赖树)
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();
}
}