LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
segm_lexicon.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 CEA LIST <gael.de-chalendar@cea.fr>
2//
3// SPDX-License-Identifier: MIT
4
5#ifndef DEEPLIMA_SEGMENTATION_IMPL_SEGM_LEXICON_H
6#define DEEPLIMA_SEGMENTATION_IMPL_SEGM_LEXICON_H
7
8#include <cstdint>
9#include <fstream>
10#include <stdexcept>
11#include <string>
12#include <unordered_set>
13
14namespace deeplima
15{
16namespace segmentation
17{
18namespace impl
19{
20
40{
41public:
42 static constexpr size_t MAX_LEN = 8;
43 static constexpr uint8_t BITS = 6;
44
45 SegmLexicon() = default;
46
47 explicit SegmLexicon(const std::string& fn)
48 {
49 load(fn);
50 }
51
52 void load(const std::string& fn)
53 {
54 std::ifstream f(fn);
55 if (!f.is_open())
56 {
57 throw std::runtime_error("Can't open the segmenter lexicon " + fn);
58 }
59 m_words.clear();
60 std::string line;
61 while (std::getline(f, line))
62 {
63 if (!line.empty() && '\r' == line.back())
64 {
65 line.pop_back();
66 }
67 const std::u32string w = utf8_to_u32(line.substr(0, line.find('\t')));
68 if (w.size() >= 2 && w.size() <= MAX_LEN)
69 {
70 m_words.insert(w);
71 }
72 }
73 }
74
75 size_t size() const
76 {
77 return m_words.size();
78 }
79
80 // The mask of the character history[n-1] (history[0..n-1] = the last n
81 // characters read, oldest first, n <= MAX_LEN).
82 uint32_t mask(const char32_t* history, size_t n) const
83 {
84 uint32_t m = 0;
85 std::u32string key;
86 key.reserve(MAX_LEN);
87 for (size_t len = 2; len <= n && len <= MAX_LEN; ++len)
88 {
89 key.assign(history + n - len, history + n);
90 if (m_words.count(key) > 0)
91 {
92 m |= 1u << (len <= 6 ? len - 2 : 5);
93 }
94 }
95 return m;
96 }
97
98 static std::u32string utf8_to_u32(const std::string& s)
99 {
100 std::u32string out;
101 for (size_t i = 0; i < s.size();)
102 {
103 const unsigned char c = s[i];
104 char32_t cp;
105 size_t n;
106 if (c < 0x80) { cp = c; n = 1; }
107 else if ((c >> 5) == 0x6) { cp = c & 0x1f; n = 2; }
108 else if ((c >> 4) == 0xe) { cp = c & 0x0f; n = 3; }
109 else if ((c >> 3) == 0x1e) { cp = c & 0x07; n = 4; }
110 else { cp = 0xfffd; n = 1; }
111 if (i + n > s.size())
112 {
113 break;
114 }
115 for (size_t k = 1; k < n; ++k)
116 {
117 cp = (cp << 6) | (static_cast<unsigned char>(s[i + k]) & 0x3f);
118 }
119 out.push_back(cp);
120 i += n;
121 }
122 return out;
123 }
124
125private:
126 std::unordered_set<std::u32string> m_words;
127};
128
129} // namespace impl
130} // namespace segmentation
131} // namespace deeplima
132
133#endif
static std::u32string utf8_to_u32(const std::string &s)
void load(const std::string &fn)
uint32_t mask(const char32_t *history, size_t n) const
Edit rules for lemmatizing words absent from the lemma dictionary.