opennlp.tools.util.featuregen.InSpanGenerator Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 opennlp.tools.util.featuregen;
import java.util.List;
import java.util.Objects;
import opennlp.tools.namefind.TokenNameFinder;
import opennlp.tools.util.Span;
/**
* Generates features if the tokens are recognized by the provided
* {@link TokenNameFinder}.
*/
public class InSpanGenerator implements AdaptiveFeatureGenerator {
private final String prefix;
private final TokenNameFinder finder;
private String[] currentSentence;
private Span[] currentNames;
/**
* Initializes a {@link InSpanGenerator} instance.
*
* @param prefix The prefix is used to distinguish the generated features
* from features generated by other instances of {@link InSpanGenerator}.
* Must not be {@code null}.
* @param finder The {@link TokenNameFinder} used to detect the names.
* Must not be {@code null}.
*/
public InSpanGenerator(String prefix, TokenNameFinder finder) {
this.prefix = Objects.requireNonNull(prefix, "prefix must not be null");
this.finder = Objects.requireNonNull(finder, "finder must not be null");
}
@Override
public void createFeatures(List features, String[] tokens, int index,
String[] preds) {
// cache results for sentence
if (currentSentence != tokens) {
currentSentence = tokens;
currentNames = finder.find(tokens);
}
// iterate over names and check if a span is contained
for (Span currentName : currentNames) {
if (currentName.contains(index)) {
// found a span for the current token
features.add(prefix + ":w=dic");
features.add(prefix + ":w=dic=" + tokens[index]);
// TODO: consider generation start and continuation features
break;
}
}
}
}