All Downloads are FREE. Search and download functionalities are using the official Maven repository.

edu.stanford.nlp.semgraph.semgrex.SemgrexBatchParser Maven / Gradle / Ivy

Go to download

Stanford CoreNLP provides a set of natural language analysis tools which can take raw English language text input and give the base forms of words, their parts of speech, whether they are names of companies, people, etc., normalize dates, times, and numeric quantities, mark up the structure of sentences in terms of phrases and word dependencies, and indicate which noun phrases refer to the same entities. It provides the foundational building blocks for higher level text understanding applications.

There is a newer version: 4.5.7
Show newest version
package edu.stanford.nlp.semgraph.semgrex; 
import edu.stanford.nlp.util.logging.Redwood;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.stanford.nlp.util.Generics;
import edu.stanford.nlp.util.Pair;

/**
 * Parses a batch of SemgrexPatterns from a stream.
 * Each SemgrexPattern must be defined in a single line.
 * This includes a preprocessor that supports macros, defined as: "macro NAME = VALUE" and used as ${NAME}
 * For example:
 *   # lines starting with the pound sign are skipped
 *   macro JOB = president|ceo|star
 *   {}=entity >appos ({lemma:/${JOB}/} >nn {ner:ORGANIZATION}=slot)
 */
public class SemgrexBatchParser  {

  /** A logger for this class */
  private static Redwood.RedwoodChannels log = Redwood.channels(SemgrexBatchParser.class);

  /** Maximum stream size in characters */
  private static final int MAX_STREAM_SIZE = 1024 * 1024;

  public static boolean VERBOSE = false;

  private SemgrexBatchParser() { } // static methods class

  public static List compileStream(InputStream is) throws IOException {
    return compileStream(is, null);
  }

  public static List compileStream(InputStream is, Env env) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    reader.mark(MAX_STREAM_SIZE);
    Map macros = preprocess(reader);
    reader.reset();
    return parse(reader, macros, env);
  }

  private static List parse(BufferedReader reader, Map macros, Env env) throws IOException {
    List patterns = new ArrayList<>();
    for(String line; (line = reader.readLine()) != null; ) {
      line = line.trim();
      if(line.isEmpty() || line.startsWith("#")) continue;
      if(line.startsWith("macro ")) continue;
      line = replaceMacros(line, macros);
      SemgrexPattern pattern = SemgrexPattern.compile(line, env);
      patterns.add(pattern);
    }
    return patterns;
  }

  private static final Pattern MACRO_NAME_PATTERN = Pattern.compile("\\$\\{[a-z0-9]+\\}", Pattern.CASE_INSENSITIVE);

  private static String replaceMacros(String line, Map macros) {
    StringBuilder out = new StringBuilder();
    Matcher matcher = MACRO_NAME_PATTERN.matcher(line);
    int offset = 0;
    while(matcher.find(offset)) {
      int start = matcher.start();
      int end = matcher.end();
      String name = line.substring(start + 2, end - 1);
      String value = macros.get(name);
      if(value == null){
        throw new RuntimeException("ERROR: Unknown macro \"" + name + "\"!");
      }
      if(start > offset) {
        out.append(line.substring(offset, start));
      }
      out.append(value);
      offset = end;
    }
    if(offset < line.length()) out.append(line.substring(offset));
    String postProcessed =  out.toString();
    if(!postProcessed.equals(line) && VERBOSE) log.info("Line \"" + line + "\" changed to \"" + postProcessed + '"');
    return postProcessed;
  }

  private static Map preprocess(BufferedReader reader) throws IOException {
    Map macros = Generics.newHashMap();
    for(String line; (line = reader.readLine()) != null; ) {
      line = line.trim();
      if(line.startsWith("macro ")){
        Pair macro = extractMacro(line);
        macros.put(macro.first(), macro.second());
      }
    }
    return macros;
  }

  private static Pair extractMacro(String line) {
    assert(line.startsWith("macro"));
    int equalPosition = line.indexOf('=');
    if(equalPosition < 0) {
      throw new RuntimeException("ERROR: Invalid syntax in macro line: \"" + line + "\"!");
    }
    String name = line.substring(5, equalPosition).trim();
    if(name.isEmpty()) {
      throw new RuntimeException("ERROR: Invalid syntax in macro line: \"" + line + "\"!");
    }
    String value = line.substring(equalPosition + 1).trim();
    if(value.isEmpty()) {
      throw new RuntimeException("ERROR: Invalid syntax in macro line: \"" + line + "\"!");
    }
    return new Pair<>(name, value);
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy