aboutsummaryrefslogtreecommitdiffstats
path: root/opennlp-linguistics/src/main/java/com/yahoo/language/opennlp/VespaCharSequenceNormalizer.java
blob: f27f9dedfae31724ae636d7e96eb4899c965af85 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.language.opennlp;

import opennlp.tools.util.normalizer.CharSequenceNormalizer;

import java.util.function.IntConsumer;
import java.util.stream.IntStream;

/**
 * Simple normalizer
 *
 * @author arnej
 */
public class VespaCharSequenceNormalizer implements CharSequenceNormalizer {

    private static final VespaCharSequenceNormalizer INSTANCE = new VespaCharSequenceNormalizer();

    public static VespaCharSequenceNormalizer getInstance() {
        return INSTANCE;
    }

    // filter replacing sequences of non-letters with a single space
    static class OnlyLetters implements IntStream.IntMapMultiConsumer {
        boolean addSpace = false;
        public void accept(int codepoint, IntConsumer target) {
            if (WordCharDetector.isWordChar(codepoint)) {
                if (addSpace) {
                    target.accept(' ');
                    addSpace = false;
                }
                target.accept(Character.toLowerCase(codepoint));
            } else {
                addSpace = true;
            }
        }
    }

    public CharSequence normalize(CharSequence text) {
        if (text.isEmpty()) {
            return text;
        }
        var r = text
                .codePoints()
                .mapMulti(new OnlyLetters())
                .collect(StringBuilder::new,
                         StringBuilder::appendCodePoint,
                         StringBuilder::append);
        return r;
    }

}