使用Stanford Parser提取包含特定单词的名词短语

时间:2014-02-09 00:49:24

标签: java nlp stanford-nlp

如何使用Stanford Parser提取包含特定单词的名词短语。我可以使用这篇文章中写的代码提取名词短语:

https://stackoverflow.com/questions/21652202/get-noun-phrase-of-subject-in-sentence-stanford-parser

但是,我需要获取包含特定单词的名词短语,但这并不像进行字符串搜索那么简单,因为该单词可以在句子中出现两次。所以我需要在句子的特定顺序中提取包含特定单词的名词短语。所以假设我有一句话:

  String some_sentence = "The dog ran after the intruding bigger dog"; 
狗出现两次,第一次作为句子中的第二个单词,第二次作为句子中的最后一个单词。如何提取包含第一次出现的狗的名词短语?

1 个答案:

答案 0 :(得分:0)

最简单的方法,如果不是最优雅的,可能是将解析收集为带括号的字符串,将其传递给正则表达式以恢复名词短语,并检查每个匹配以查看它是否包含该单词。

这会产生某种类似的东西:

String parse  = "(ROOT (S (NP (DT The) (NN dog)) (VP (VBD ran) (PP (IN after) (NP (DT the) (JJ intruding) (JJR bigger) (NN dog))))))";
String target = "dog";
String result = null;
String regex  = "\\(NP \\s (?: \\( .+? \\) )* \\)"; // an NP contains an arbitrary number of sub-phrases
Pattern patt  = Pattern.compile(regex, Pattern.COMMENTS);
Matcher match = patt.matcher(parse);
while(match.find() && result == null) {
    if (match.group().contains(target)) {
        result = match.group();
    }
}
if (result != null) {
    System.out.println(result);
}