如何在StanfordNLP中修改TokenRegex规则?

时间:2017-05-02 07:50:46

标签: java stanford-nlp

我将tokenregex的规则文件作为

$EDU_FIRST_KEYWORD = (/Education/|/Course[s]?/|/Educational/|/Academic/|/Education/ /and/?|/Professional/|/Certification[s]?/ /and/?)

$EDU_LAST_KEYWORD = (/Background/|/Qualification[s]?/|/Training[s]?/|/Detail[s]?/|/Record[s]?/) tokens = { type: "CLASS", value: "edu.stanford.nlp.ling.CoreAnnotations$NamedEntityTagAnnotation" }

{ ruleType: "tokens", pattern: ( $EDU_FIRST_KEYWORD $EDU_LAST_KEYWORD ?), result: "EDUCATION" }

我希望匹配EDU_FIRST_KEYWORD后跟EDU_LAST_KEYWORD。如果它与两个部分都不匹配,则检查EDU_FIRST_KEYWORD是否与给定字符串匹配。

E.g。 1.培训与发展课程

匹配输出:教育(因为它匹配课程,不应该发生)

预期输出:无输出

这是因为与字符串的第一部分或完整字符串不匹配。

  1. 教育背景
  2. 匹配输出:教育

    预期产出:教育

    我尝试将pattern: ( $EDU_FIRST_KEYWORD $EDU_LAST_KEYWORD ?)更改为 pattern: ( $EDU_FIRST_KEYWORD + $EDU_LAST_KEYWORD ?)但它没有帮助。

    我尝试过stanfordNLP tokenregex文档,但无法获得如何实现这一点。有人可以帮我改变规则文件吗? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您希望使用TokenSequenceMatcher的matches()方法让规则针对整个String运行。

如果您使用find(),它将搜索整个字符串...如果您使用matches(),它将查看整个字符串是否与模式匹配。

目前我不确定TokensRegexAnnotator是否可以对句子执行完整的字符串匹配,所以你可能需要使用这样的代码:

package edu.stanford.nlp.examples;

import edu.stanford.nlp.util.*;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.ling.tokensregex.Env;
import edu.stanford.nlp.ling.tokensregex.TokenSequencePattern;
import edu.stanford.nlp.ling.tokensregex.TokenSequenceMatcher;
import edu.stanford.nlp.pipeline.*;

import java.util.*;

public class TokensRegexExactMatch {

  public static void main(String[] args) {
    Properties props = new Properties();
    props.setProperty("annotators", "tokenize");
    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
    Annotation annotation = new Annotation("Training & Courses");
    pipeline.annotate(annotation);
    //System.err.println(IOUtils.stringFromFile("course.rules"));
    Env env = TokenSequencePattern.getNewEnv();
    env.bind("$EDU_WORD_ONE", "/Education|Educational|Courses/");
    env.bind("$EDU_WORD_TWO", "/Background|Qualification/");
    TokenSequencePattern pattern = TokenSequencePattern.compile(env, "$EDU_WORD_ONE $EDU_WORD_TWO?");
    List<CoreLabel> tokens = annotation.get(CoreAnnotations.TokensAnnotation.class);
    TokenSequenceMatcher matcher = pattern.getMatcher(tokens);
    // matcher.matches()
    while (matcher.find()) {
      System.err.println("---");
      String matchedString = matcher.group();
      List<CoreMap> matchedTokens = matcher.groupNodes();
      System.err.println(matchedTokens);
    }
  }
}
相关问题