我刚刚开始玩弄斯坦福解析器,所以对此持保留态度。
我要提取一个名词及其相应的形容词或与该特定名词相关的任何必需信息,我会做的是:
生成句子的解析树。(查看 ParserDemo.java 以了解如何执行此操作)。
https://wiki.csc.calpoly.edu/CSC-581-S11-06/browser/trunk/Stanford/stanford-parser-2011-04-20/src/edu/stanford/nlp/parser/lexparser/demo/ ParserDemo.java?rev=2
解析树将如下所示:
(ROOT
(S
(NP (JJ handsome) (NNP Joe) (NNP Blow))
(VP (VBD sent)
(NP (DT an) (NN email))
(PP (TO to)
(NP (PRP$ his) (JJ congressional) (NN representative))))))
对于这样的一句话:英俊的乔布洛给他的国会代表发了一封电子邮件
然后您编写一些代码以递归方式遍历解析树并挑选出“NP”片段。
例如,一个这样的片段是 (NP (JJ nice) (NNP Joe) (NNP Blow))
一旦你有了那个片段,你就可以收集所有你感兴趣的形容词和任何其他修饰语。了解代码的含义很有帮助 [ http://bulba.sdsu.edu/jeanette/thesis/PennTags.html ]
我编写了一些代码来爬回解析树并提取内容...这可能会帮助您入门>
不能给你所有的代码,但这里有一些......
static {
nounNodeNames = new ArrayList<String>();
nounNodeNames.add( "NP");
nounNodeNames.add( "NPS");
nounNodeNames.add( "FW");
nounNodeNames.add( "NN");
nounNodeNames.add( "NNS");
nounNodeNames.add( "NNP");
nounNodeNames.add( "NNPS");
}
public List<NounPhrase> extractPhrasesFromString(Tree tree, String originalString) {
List<NounPhrase> foundPhraseNodes = new ArrayList<NounPhrase>();
collect(tree, foundPhraseNodes);
logger.debug("parsing " + originalString + " yields " + foundPhraseNodes.size() + " noun node(s).");
if (foundPhraseNodes.size() == 0) {
foundPhraseNodes.add(new NounPhrase(tree, originalString));
}
return foundPhraseNodes;
}
private void collect(Tree tree, List<NounPhrase> foundPhraseNodes) {
if (tree == null || tree.isLeaf()) {
return;
}
Label label = tree.label();
if (label instanceof CoreLabel) {
CoreLabel coreLabel = ((CoreLabel) label);
String text = ((CoreLabel) label).getString(CoreAnnotations.OriginalTextAnnotation.class);
logger.debug(" got text: " + text);
if (text.equals("THE")) {
logger.debug(" got THE text: " + text);
}
String category = coreLabel.getString(CoreAnnotations.CategoryAnnotation.class);
if (nounNodeNames.contains(category)) {
NounPhrase phrase = null;
String phraseString = flatten(tree);
if ((phrase = stringToNounPhrase.get(phraseString)) == null) {
phrase = new NounPhrase(tree, phraseString);
stringToNounPhrase.put(phraseString, phrase);
}
if (! foundPhraseNodes.contains(phrase)) {
logger.debug("adding found noun phrase to list: {}", phrase.debug());
foundPhraseNodes.add(phrase);
} else {
logger.debug("on list already, so skipping found noun phrase: {}", phrase.debug());
}
}
}
List<Tree> kids = tree.getChildrenAsList();
for (Tree kid : kids) {
collect(kid, foundPhraseNodes);
}
}