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

org.cogroo.util.EntityUtils Maven / Gradle / Ivy

There is a newer version: 4.3.1
Show newest version
/**
 * Copyright (C) 2012 cogroo 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cogroo.util;

import java.util.ArrayList;
import java.util.List;

import opennlp.tools.util.Span;

import org.cogroo.text.Token;
import org.cogroo.text.impl.TokenImpl;

public class EntityUtils {

  public static List groupTokensChar(String text, List toks,
      List charSpans, String additionalContext) {
    if (charSpans == null || charSpans.size() == 0) {
      return toks;
    }

    int lastVisitedTok = 0;
    List spans = new ArrayList(charSpans.size());

    for (Span ch : charSpans) {
      // System.out.println("looking for: " + ch.getCoveredText(text));
      Token aToken = toks.get(lastVisitedTok);
      while (aToken.getStart() < ch.getStart()) {
        lastVisitedTok++;
        aToken = toks.get(lastVisitedTok);
      }
      int start = lastVisitedTok;
      while (aToken.getEnd() < ch.getEnd()) {
        lastVisitedTok++;
        aToken = toks.get(lastVisitedTok);
      }
      int end = lastVisitedTok + 1;
      Span tokSpan = new Span(start, end);
      spans.add(tokSpan);
    }

    return groupTokens(text, toks, spans, additionalContext);
  }

  public static List groupTokens(String text, List toks,
      List spans) {
    return groupTokens(text, toks, spans, null);
  }

  public static List groupTokens(String text, List toks,
      List spans, String additionalContext) {
    for (int i = spans.size() - 1; i >= 0; i--) {
      Span span = spans.get(i);
      if (span.length() > 0) {
        int s = toks.get(span.getStart()).getStart();
        int e = toks.get(span.getEnd() - 1).getEnd();
        String lexeme = text.substring(s, e).replace(" ", "_");

        List removeToks = new ArrayList();
        for (int j = span.getEnd() - 1; j >= span.getStart(); j--) {
          removeToks.add(toks.remove(j));
        }
        Token t = new TokenImpl(s, e, lexeme);
        t.setPOSTag(span.getType());

        // if(additionalContext != null) {
        // t.addContext(analyzer, additionalContext);
        // t.setAdditionalContext(additionalContext);
        // }

        toks.add(span.getStart(), t);
      }
    }
    return toks;
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy