aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/tokenizer/split.cpp
blob: d6f1345aad1281093193268a1351a345eb48cc2b (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "split.h"

#include "tokenizer.h"

namespace {
    class TSimpleTokenHandler: public ITokenHandler {
    public:
        TSimpleTokenHandler(TVector<TUtf16String>* outTokens, const TTokenizerSplitParams& params)
            : Tokens(outTokens)
            , Params(params)
        {
        }

        void OnToken(const TWideToken& token, size_t, NLP_TYPE type) override {
            if (!Params.HandledMask.SafeTest(type)) {
                return;
            }

            Tokens->push_back(TUtf16String(token.Token, token.Leng));
        }

    private:
        TVector<TUtf16String>* Tokens;
        TTokenizerSplitParams Params;
    };

    class TSimpleSentenceHandler: public ITokenHandler {
    public:
        TSimpleSentenceHandler(TVector<TUtf16String>* sentences)
            : Sentences(sentences)
        {
        }

        void OnToken(const TWideToken& token, size_t, NLP_TYPE type) override {
            CurToken += token.Text();

            if (type == NLP_SENTBREAK || type == NLP_PARABREAK) {
                Flush();
            }
        }

        void Flush() {
            if (!CurToken.empty()) {
                Sentences->push_back(CurToken);

                CurToken = TUtf16String();
            }
        }

    private:
        TUtf16String CurToken;
        TVector<TUtf16String>* Sentences;
    };
}

const TTokenizerSplitParams::THandledMask TTokenizerSplitParams::WORDS(NLP_WORD);
const TTokenizerSplitParams::THandledMask TTokenizerSplitParams::NOT_PUNCT(NLP_WORD, NLP_INTEGER, NLP_FLOAT, NLP_MARK);

TVector<TUtf16String> SplitIntoTokens(const TUtf16String& text, const TTokenizerSplitParams& params) {
    TVector<TUtf16String> words;

    TSimpleTokenHandler handler(&words, params);
    TNlpTokenizer tokenizer(handler, params.BackwardCompatibility);
    TTokenizerOptions opts { params.SpacePreserve, params.TokenizerLangMask, params.UrlDecode };
    tokenizer.Tokenize(text.data(), text.size(), opts);

    return words;
}

TVector<TUtf16String> SplitIntoSentences(const TUtf16String& text, const TTokenizerSplitParams& params) {
    TVector<TUtf16String> sentences;

    TSimpleSentenceHandler handler(&sentences);
    TNlpTokenizer tokenizer(handler, params.BackwardCompatibility);
    TTokenizerOptions opts { params.SpacePreserve, params.TokenizerLangMask, params.UrlDecode };
    tokenizer.Tokenize(text.data(), text.size(), opts);
    handler.Flush();

    return sentences;
}