@ohos-ports/nodejieba 0.0.0-stage → 3.5.8-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +360 -0
  2. package/LICENSE +21 -0
  3. package/README.md +270 -2
  4. package/binding.gyp +63 -0
  5. package/build/Release/nodejieba.node +0 -0
  6. package/index.js +77 -0
  7. package/lib/index.cpp +3 -0
  8. package/lib/nodejieba.cpp +218 -0
  9. package/lib/nodejieba.h +28 -0
  10. package/lib/utils.h +47 -0
  11. package/package.json +62 -4
  12. package/submodules/cppjieba/CHANGELOG.md +305 -0
  13. package/submodules/cppjieba/deps/limonp/CHANGELOG.md +160 -0
  14. package/submodules/cppjieba/deps/limonp/include/limonp/ArgvContext.hpp +70 -0
  15. package/submodules/cppjieba/deps/limonp/include/limonp/Closure.hpp +206 -0
  16. package/submodules/cppjieba/deps/limonp/include/limonp/Colors.hpp +31 -0
  17. package/submodules/cppjieba/deps/limonp/include/limonp/Condition.hpp +38 -0
  18. package/submodules/cppjieba/deps/limonp/include/limonp/Config.hpp +103 -0
  19. package/submodules/cppjieba/deps/limonp/include/limonp/ForcePublic.hpp +7 -0
  20. package/submodules/cppjieba/deps/limonp/include/limonp/LocalVector.hpp +139 -0
  21. package/submodules/cppjieba/deps/limonp/include/limonp/Logging.hpp +90 -0
  22. package/submodules/cppjieba/deps/limonp/include/limonp/NonCopyable.hpp +21 -0
  23. package/submodules/cppjieba/deps/limonp/include/limonp/StdExtension.hpp +157 -0
  24. package/submodules/cppjieba/deps/limonp/include/limonp/StringUtil.hpp +386 -0
  25. package/submodules/cppjieba/dict/README.md +31 -0
  26. package/submodules/cppjieba/dict/hmm_model.utf8 +34 -0
  27. package/submodules/cppjieba/dict/idf.utf8 +258826 -0
  28. package/submodules/cppjieba/dict/jieba.dict.utf8 +348982 -0
  29. package/submodules/cppjieba/dict/pos_dict/char_state_tab.utf8 +6653 -0
  30. package/submodules/cppjieba/dict/pos_dict/prob_emit.utf8 +166 -0
  31. package/submodules/cppjieba/dict/pos_dict/prob_start.utf8 +259 -0
  32. package/submodules/cppjieba/dict/pos_dict/prob_trans.utf8 +5222 -0
  33. package/submodules/cppjieba/dict/stop_words.utf8 +1534 -0
  34. package/submodules/cppjieba/dict/user.dict.utf8 +4 -0
  35. package/submodules/cppjieba/include/cppjieba/DictTrie.hpp +285 -0
  36. package/submodules/cppjieba/include/cppjieba/FullSegment.hpp +93 -0
  37. package/submodules/cppjieba/include/cppjieba/HMMModel.hpp +129 -0
  38. package/submodules/cppjieba/include/cppjieba/HMMSegment.hpp +190 -0
  39. package/submodules/cppjieba/include/cppjieba/Jieba.hpp +169 -0
  40. package/submodules/cppjieba/include/cppjieba/KeywordExtractor.hpp +153 -0
  41. package/submodules/cppjieba/include/cppjieba/MPSegment.hpp +137 -0
  42. package/submodules/cppjieba/include/cppjieba/MixSegment.hpp +109 -0
  43. package/submodules/cppjieba/include/cppjieba/PosTagger.hpp +77 -0
  44. package/submodules/cppjieba/include/cppjieba/PreFilter.hpp +54 -0
  45. package/submodules/cppjieba/include/cppjieba/QuerySegment.hpp +89 -0
  46. package/submodules/cppjieba/include/cppjieba/SegmentBase.hpp +46 -0
  47. package/submodules/cppjieba/include/cppjieba/SegmentTagged.hpp +23 -0
  48. package/submodules/cppjieba/include/cppjieba/TextRankExtractor.hpp +190 -0
  49. package/submodules/cppjieba/include/cppjieba/Trie.hpp +200 -0
  50. package/submodules/cppjieba/include/cppjieba/Unicode.hpp +227 -0
  51. package/test/load_dict_test.js +14 -0
  52. package/test/missing_binding_test.js +42 -0
  53. package/test/test.js +366 -0
  54. package/test/testdata/userdict.utf8 +1 -0
  55. package/types/index.d.ts +30 -0
@@ -0,0 +1,4 @@
1
+ 云计算
2
+ 韩玉鉴赏
3
+ 蓝翔 nz
4
+ 区块链 10 nz
@@ -0,0 +1,285 @@
1
+ #ifndef CPPJIEBA_DICT_TRIE_HPP
2
+ #define CPPJIEBA_DICT_TRIE_HPP
3
+
4
+ #include <iostream>
5
+ #include <fstream>
6
+ #include <map>
7
+ #include <string>
8
+ #include <cstring>
9
+ #include <cstdlib>
10
+ #include <stdint.h>
11
+ #include <cmath>
12
+ #include <limits>
13
+ #include "limonp/StringUtil.hpp"
14
+ #include "limonp/Logging.hpp"
15
+ #include "Unicode.hpp"
16
+ #include "Trie.hpp"
17
+
18
+ namespace cppjieba {
19
+
20
+ using namespace limonp;
21
+
22
+ const double MIN_DOUBLE = -3.14e+100;
23
+ const double MAX_DOUBLE = 3.14e+100;
24
+ const size_t DICT_COLUMN_NUM = 3;
25
+ const char* const UNKNOWN_TAG = "";
26
+
27
+ class DictTrie {
28
+ public:
29
+ enum UserWordWeightOption {
30
+ WordWeightMin,
31
+ WordWeightMedian,
32
+ WordWeightMax,
33
+ }; // enum UserWordWeightOption
34
+
35
+ DictTrie(const string& dict_path, const string& user_dict_paths = "", UserWordWeightOption user_word_weight_opt = WordWeightMedian) {
36
+ Init(dict_path, user_dict_paths, user_word_weight_opt);
37
+ }
38
+
39
+ ~DictTrie() {
40
+ delete trie_;
41
+ }
42
+
43
+ bool InsertUserWord(const string& word, const string& tag = UNKNOWN_TAG) {
44
+ DictUnit node_info;
45
+ if (!MakeNodeInfo(node_info, word, user_word_default_weight_, tag)) {
46
+ return false;
47
+ }
48
+ active_node_infos_.push_back(node_info);
49
+ trie_->InsertNode(node_info.word, &active_node_infos_.back());
50
+ return true;
51
+ }
52
+
53
+ bool InsertUserWord(const string& word,int freq, const string& tag = UNKNOWN_TAG) {
54
+ DictUnit node_info;
55
+ double weight = freq ? log(1.0 * freq / freq_sum_) : user_word_default_weight_ ;
56
+ if (!MakeNodeInfo(node_info, word, weight , tag)) {
57
+ return false;
58
+ }
59
+ active_node_infos_.push_back(node_info);
60
+ trie_->InsertNode(node_info.word, &active_node_infos_.back());
61
+ return true;
62
+ }
63
+
64
+ bool DeleteUserWord(const string& word, const string& tag = UNKNOWN_TAG) {
65
+ DictUnit node_info;
66
+ if (!MakeNodeInfo(node_info, word, user_word_default_weight_, tag)) {
67
+ return false;
68
+ }
69
+ trie_->DeleteNode(node_info.word, &node_info);
70
+ return true;
71
+ }
72
+
73
+ const DictUnit* Find(RuneStrArray::const_iterator begin, RuneStrArray::const_iterator end) const {
74
+ return trie_->Find(begin, end);
75
+ }
76
+
77
+ void Find(RuneStrArray::const_iterator begin,
78
+ RuneStrArray::const_iterator end,
79
+ vector<struct Dag>&res,
80
+ size_t max_word_len = MAX_WORD_LENGTH) const {
81
+ trie_->Find(begin, end, res, max_word_len);
82
+ }
83
+
84
+ bool Find(const string& word)
85
+ {
86
+ const DictUnit *tmp = NULL;
87
+ RuneStrArray runes;
88
+ if (!DecodeUTF8RunesInString(word, runes))
89
+ {
90
+ XLOG(ERROR) << "Decode failed.";
91
+ }
92
+ tmp = Find(runes.begin(), runes.end());
93
+ if (tmp == NULL)
94
+ {
95
+ return false;
96
+ }
97
+ else
98
+ {
99
+ return true;
100
+ }
101
+ }
102
+
103
+ bool IsUserDictSingleChineseWord(const Rune& word) const {
104
+ return IsIn(user_dict_single_chinese_word_, word);
105
+ }
106
+
107
+ double GetMinWeight() const {
108
+ return min_weight_;
109
+ }
110
+
111
+ void InserUserDictNode(const string& line) {
112
+ vector<string> buf;
113
+ DictUnit node_info;
114
+ Split(line, buf, " ");
115
+ if(buf.size() == 1){
116
+ MakeNodeInfo(node_info,
117
+ buf[0],
118
+ user_word_default_weight_,
119
+ UNKNOWN_TAG);
120
+ } else if (buf.size() == 2) {
121
+ MakeNodeInfo(node_info,
122
+ buf[0],
123
+ user_word_default_weight_,
124
+ buf[1]);
125
+ } else if (buf.size() == 3) {
126
+ int freq = atoi(buf[1].c_str());
127
+ assert(freq_sum_ > 0.0);
128
+ double weight = log(1.0 * freq / freq_sum_);
129
+ MakeNodeInfo(node_info, buf[0], weight, buf[2]);
130
+ }
131
+ static_node_infos_.push_back(node_info);
132
+ if (node_info.word.size() == 1) {
133
+ user_dict_single_chinese_word_.insert(node_info.word[0]);
134
+ }
135
+ }
136
+
137
+ void LoadUserDict(const vector<string>& buf) {
138
+ for (size_t i = 0; i < buf.size(); i++) {
139
+ InserUserDictNode(buf[i]);
140
+ }
141
+ }
142
+
143
+ void LoadUserDict(const set<string>& buf) {
144
+ std::set<string>::const_iterator iter;
145
+ for (iter = buf.begin(); iter != buf.end(); iter++){
146
+ InserUserDictNode(*iter);
147
+ }
148
+ }
149
+
150
+ void LoadUserDict(const string& filePaths) {
151
+ vector<string> files = limonp::Split(filePaths, "|;");
152
+ for (size_t i = 0; i < files.size(); i++) {
153
+ ifstream ifs(files[i].c_str());
154
+ XCHECK(ifs.is_open()) << "open " << files[i] << " failed";
155
+ string line;
156
+
157
+ while(getline(ifs, line)) {
158
+ if (line.size() == 0) {
159
+ continue;
160
+ }
161
+ InserUserDictNode(line);
162
+ }
163
+ }
164
+ }
165
+
166
+
167
+ private:
168
+ void Init(const string& dict_path, const string& user_dict_paths, UserWordWeightOption user_word_weight_opt) {
169
+ LoadDict(dict_path);
170
+ freq_sum_ = CalcFreqSum(static_node_infos_);
171
+ CalculateWeight(static_node_infos_, freq_sum_);
172
+ SetStaticWordWeights(user_word_weight_opt);
173
+
174
+ if (user_dict_paths.size()) {
175
+ LoadUserDict(user_dict_paths);
176
+ }
177
+ Shrink(static_node_infos_);
178
+ CreateTrie(static_node_infos_);
179
+ }
180
+
181
+ void CreateTrie(const vector<DictUnit>& dictUnits) {
182
+ assert(dictUnits.size());
183
+ vector<Unicode> words;
184
+ vector<const DictUnit*> valuePointers;
185
+ for (size_t i = 0 ; i < dictUnits.size(); i ++) {
186
+ words.push_back(dictUnits[i].word);
187
+ valuePointers.push_back(&dictUnits[i]);
188
+ }
189
+
190
+ trie_ = new Trie(words, valuePointers);
191
+ }
192
+
193
+
194
+
195
+
196
+ bool MakeNodeInfo(DictUnit& node_info,
197
+ const string& word,
198
+ double weight,
199
+ const string& tag) {
200
+ if (!DecodeUTF8RunesInString(word, node_info.word)) {
201
+ XLOG(ERROR) << "UTF-8 decode failed for dict word: " << word;
202
+ return false;
203
+ }
204
+ node_info.weight = weight;
205
+ node_info.tag = tag;
206
+ return true;
207
+ }
208
+
209
+ void LoadDict(const string& filePath) {
210
+ ifstream ifs(filePath.c_str());
211
+ XCHECK(ifs.is_open()) << "open " << filePath << " failed.";
212
+ string line;
213
+ vector<string> buf;
214
+
215
+ DictUnit node_info;
216
+ while (getline(ifs, line)) {
217
+ Split(line, buf, " ");
218
+ XCHECK(buf.size() == DICT_COLUMN_NUM) << "split result illegal, line:" << line;
219
+ MakeNodeInfo(node_info,
220
+ buf[0],
221
+ atof(buf[1].c_str()),
222
+ buf[2]);
223
+ static_node_infos_.push_back(node_info);
224
+ }
225
+ }
226
+
227
+ static bool WeightCompare(const DictUnit& lhs, const DictUnit& rhs) {
228
+ return lhs.weight < rhs.weight;
229
+ }
230
+
231
+ void SetStaticWordWeights(UserWordWeightOption option) {
232
+ XCHECK(!static_node_infos_.empty());
233
+ vector<DictUnit> x = static_node_infos_;
234
+ sort(x.begin(), x.end(), WeightCompare);
235
+ min_weight_ = x[0].weight;
236
+ max_weight_ = x[x.size() - 1].weight;
237
+ median_weight_ = x[x.size() / 2].weight;
238
+ switch (option) {
239
+ case WordWeightMin:
240
+ user_word_default_weight_ = min_weight_;
241
+ break;
242
+ case WordWeightMedian:
243
+ user_word_default_weight_ = median_weight_;
244
+ break;
245
+ default:
246
+ user_word_default_weight_ = max_weight_;
247
+ break;
248
+ }
249
+ }
250
+
251
+ double CalcFreqSum(const vector<DictUnit>& node_infos) const {
252
+ double sum = 0.0;
253
+ for (size_t i = 0; i < node_infos.size(); i++) {
254
+ sum += node_infos[i].weight;
255
+ }
256
+ return sum;
257
+ }
258
+
259
+ void CalculateWeight(vector<DictUnit>& node_infos, double sum) const {
260
+ assert(sum > 0.0);
261
+ for (size_t i = 0; i < node_infos.size(); i++) {
262
+ DictUnit& node_info = node_infos[i];
263
+ assert(node_info.weight > 0.0);
264
+ node_info.weight = log(double(node_info.weight)/sum);
265
+ }
266
+ }
267
+
268
+ void Shrink(vector<DictUnit>& units) const {
269
+ vector<DictUnit>(units.begin(), units.end()).swap(units);
270
+ }
271
+
272
+ vector<DictUnit> static_node_infos_;
273
+ deque<DictUnit> active_node_infos_; // must not be vector
274
+ Trie * trie_;
275
+
276
+ double freq_sum_;
277
+ double min_weight_;
278
+ double max_weight_;
279
+ double median_weight_;
280
+ double user_word_default_weight_;
281
+ unordered_set<Rune> user_dict_single_chinese_word_;
282
+ };
283
+ }
284
+
285
+ #endif
@@ -0,0 +1,93 @@
1
+ #ifndef CPPJIEBA_FULLSEGMENT_H
2
+ #define CPPJIEBA_FULLSEGMENT_H
3
+
4
+ #include <algorithm>
5
+ #include <set>
6
+ #include <cassert>
7
+ #include "limonp/Logging.hpp"
8
+ #include "DictTrie.hpp"
9
+ #include "SegmentBase.hpp"
10
+ #include "Unicode.hpp"
11
+
12
+ namespace cppjieba {
13
+ class FullSegment: public SegmentBase {
14
+ public:
15
+ FullSegment(const string& dictPath) {
16
+ dictTrie_ = new DictTrie(dictPath);
17
+ isNeedDestroy_ = true;
18
+ }
19
+ FullSegment(const DictTrie* dictTrie)
20
+ : dictTrie_(dictTrie), isNeedDestroy_(false) {
21
+ assert(dictTrie_);
22
+ }
23
+ ~FullSegment() {
24
+ if (isNeedDestroy_) {
25
+ delete dictTrie_;
26
+ }
27
+ }
28
+ void Cut(const string& sentence,
29
+ vector<string>& words) const {
30
+ vector<Word> tmp;
31
+ Cut(sentence, tmp);
32
+ GetStringsFromWords(tmp, words);
33
+ }
34
+ void Cut(const string& sentence,
35
+ vector<Word>& words) const {
36
+ PreFilter pre_filter(symbols_, sentence);
37
+ PreFilter::Range range;
38
+ vector<WordRange> wrs;
39
+ wrs.reserve(sentence.size()/2);
40
+ while (pre_filter.HasNext()) {
41
+ range = pre_filter.Next();
42
+ Cut(range.begin, range.end, wrs);
43
+ }
44
+ words.clear();
45
+ words.reserve(wrs.size());
46
+ GetWordsFromWordRanges(sentence, wrs, words);
47
+ }
48
+ void Cut(RuneStrArray::const_iterator begin,
49
+ RuneStrArray::const_iterator end,
50
+ vector<WordRange>& res) const {
51
+ // result of searching in trie tree
52
+ LocalVector<pair<size_t, const DictUnit*> > tRes;
53
+
54
+ // max index of res's words
55
+ size_t maxIdx = 0;
56
+
57
+ // always equals to (uItr - begin)
58
+ size_t uIdx = 0;
59
+
60
+ // tmp variables
61
+ size_t wordLen = 0;
62
+ assert(dictTrie_);
63
+ vector<struct Dag> dags;
64
+ dictTrie_->Find(begin, end, dags);
65
+ for (size_t i = 0; i < dags.size(); i++) {
66
+ for (size_t j = 0; j < dags[i].nexts.size(); j++) {
67
+ size_t nextoffset = dags[i].nexts[j].first;
68
+ assert(nextoffset < dags.size());
69
+ const DictUnit* du = dags[i].nexts[j].second;
70
+ if (du == NULL) {
71
+ if (dags[i].nexts.size() == 1 && maxIdx <= uIdx) {
72
+ WordRange wr(begin + i, begin + nextoffset);
73
+ res.push_back(wr);
74
+ }
75
+ } else {
76
+ wordLen = du->word.size();
77
+ if (wordLen >= 2 || (dags[i].nexts.size() == 1 && maxIdx <= uIdx)) {
78
+ WordRange wr(begin + i, begin + nextoffset);
79
+ res.push_back(wr);
80
+ }
81
+ }
82
+ maxIdx = uIdx + wordLen > maxIdx ? uIdx + wordLen : maxIdx;
83
+ }
84
+ uIdx++;
85
+ }
86
+ }
87
+ private:
88
+ const DictTrie* dictTrie_;
89
+ bool isNeedDestroy_;
90
+ };
91
+ }
92
+
93
+ #endif
@@ -0,0 +1,129 @@
1
+ #ifndef CPPJIEBA_HMMMODEL_H
2
+ #define CPPJIEBA_HMMMODEL_H
3
+
4
+ #include "limonp/StringUtil.hpp"
5
+ #include "Trie.hpp"
6
+
7
+ namespace cppjieba {
8
+
9
+ using namespace limonp;
10
+ typedef unordered_map<Rune, double> EmitProbMap;
11
+
12
+ struct HMMModel {
13
+ /*
14
+ * STATUS:
15
+ * 0: HMMModel::B, 1: HMMModel::E, 2: HMMModel::M, 3:HMMModel::S
16
+ * */
17
+ enum {B = 0, E = 1, M = 2, S = 3, STATUS_SUM = 4};
18
+
19
+ HMMModel(const string& modelPath) {
20
+ memset(startProb, 0, sizeof(startProb));
21
+ memset(transProb, 0, sizeof(transProb));
22
+ statMap[0] = 'B';
23
+ statMap[1] = 'E';
24
+ statMap[2] = 'M';
25
+ statMap[3] = 'S';
26
+ emitProbVec.push_back(&emitProbB);
27
+ emitProbVec.push_back(&emitProbE);
28
+ emitProbVec.push_back(&emitProbM);
29
+ emitProbVec.push_back(&emitProbS);
30
+ LoadModel(modelPath);
31
+ }
32
+ ~HMMModel() {
33
+ }
34
+ void LoadModel(const string& filePath) {
35
+ ifstream ifile(filePath.c_str());
36
+ XCHECK(ifile.is_open()) << "open " << filePath << " failed";
37
+ string line;
38
+ vector<string> tmp;
39
+ vector<string> tmp2;
40
+ //Load startProb
41
+ XCHECK(GetLine(ifile, line));
42
+ Split(line, tmp, " ");
43
+ XCHECK(tmp.size() == STATUS_SUM);
44
+ for (size_t j = 0; j< tmp.size(); j++) {
45
+ startProb[j] = atof(tmp[j].c_str());
46
+ }
47
+
48
+ //Load transProb
49
+ for (size_t i = 0; i < STATUS_SUM; i++) {
50
+ XCHECK(GetLine(ifile, line));
51
+ Split(line, tmp, " ");
52
+ XCHECK(tmp.size() == STATUS_SUM);
53
+ for (size_t j =0; j < STATUS_SUM; j++) {
54
+ transProb[i][j] = atof(tmp[j].c_str());
55
+ }
56
+ }
57
+
58
+ //Load emitProbB
59
+ XCHECK(GetLine(ifile, line));
60
+ XCHECK(LoadEmitProb(line, emitProbB));
61
+
62
+ //Load emitProbE
63
+ XCHECK(GetLine(ifile, line));
64
+ XCHECK(LoadEmitProb(line, emitProbE));
65
+
66
+ //Load emitProbM
67
+ XCHECK(GetLine(ifile, line));
68
+ XCHECK(LoadEmitProb(line, emitProbM));
69
+
70
+ //Load emitProbS
71
+ XCHECK(GetLine(ifile, line));
72
+ XCHECK(LoadEmitProb(line, emitProbS));
73
+ }
74
+ double GetEmitProb(const EmitProbMap* ptMp, Rune key,
75
+ double defVal)const {
76
+ EmitProbMap::const_iterator cit = ptMp->find(key);
77
+ if (cit == ptMp->end()) {
78
+ return defVal;
79
+ }
80
+ return cit->second;
81
+ }
82
+ bool GetLine(ifstream& ifile, string& line) {
83
+ while (getline(ifile, line)) {
84
+ Trim(line);
85
+ if (line.empty()) {
86
+ continue;
87
+ }
88
+ if (StartsWith(line, "#")) {
89
+ continue;
90
+ }
91
+ return true;
92
+ }
93
+ return false;
94
+ }
95
+ bool LoadEmitProb(const string& line, EmitProbMap& mp) {
96
+ if (line.empty()) {
97
+ return false;
98
+ }
99
+ vector<string> tmp, tmp2;
100
+ Unicode unicode;
101
+ Split(line, tmp, ",");
102
+ for (size_t i = 0; i < tmp.size(); i++) {
103
+ Split(tmp[i], tmp2, ":");
104
+ if (2 != tmp2.size()) {
105
+ XLOG(ERROR) << "emitProb illegal.";
106
+ return false;
107
+ }
108
+ if (!DecodeUTF8RunesInString(tmp2[0], unicode) || unicode.size() != 1) {
109
+ XLOG(ERROR) << "TransCode failed.";
110
+ return false;
111
+ }
112
+ mp[unicode[0]] = atof(tmp2[1].c_str());
113
+ }
114
+ return true;
115
+ }
116
+
117
+ char statMap[STATUS_SUM];
118
+ double startProb[STATUS_SUM];
119
+ double transProb[STATUS_SUM][STATUS_SUM];
120
+ EmitProbMap emitProbB;
121
+ EmitProbMap emitProbE;
122
+ EmitProbMap emitProbM;
123
+ EmitProbMap emitProbS;
124
+ vector<EmitProbMap* > emitProbVec;
125
+ }; // struct HMMModel
126
+
127
+ } // namespace cppjieba
128
+
129
+ #endif
@@ -0,0 +1,190 @@
1
+ #ifndef CPPJIBEA_HMMSEGMENT_H
2
+ #define CPPJIBEA_HMMSEGMENT_H
3
+
4
+ #include <iostream>
5
+ #include <fstream>
6
+ #include <memory.h>
7
+ #include <cassert>
8
+ #include "HMMModel.hpp"
9
+ #include "SegmentBase.hpp"
10
+
11
+ namespace cppjieba {
12
+ class HMMSegment: public SegmentBase {
13
+ public:
14
+ HMMSegment(const string& filePath)
15
+ : model_(new HMMModel(filePath)), isNeedDestroy_(true) {
16
+ }
17
+ HMMSegment(const HMMModel* model)
18
+ : model_(model), isNeedDestroy_(false) {
19
+ }
20
+ ~HMMSegment() {
21
+ if (isNeedDestroy_) {
22
+ delete model_;
23
+ }
24
+ }
25
+
26
+ void Cut(const string& sentence,
27
+ vector<string>& words) const {
28
+ vector<Word> tmp;
29
+ Cut(sentence, tmp);
30
+ GetStringsFromWords(tmp, words);
31
+ }
32
+ void Cut(const string& sentence,
33
+ vector<Word>& words) const {
34
+ PreFilter pre_filter(symbols_, sentence);
35
+ PreFilter::Range range;
36
+ vector<WordRange> wrs;
37
+ wrs.reserve(sentence.size()/2);
38
+ while (pre_filter.HasNext()) {
39
+ range = pre_filter.Next();
40
+ Cut(range.begin, range.end, wrs);
41
+ }
42
+ words.clear();
43
+ words.reserve(wrs.size());
44
+ GetWordsFromWordRanges(sentence, wrs, words);
45
+ }
46
+ void Cut(RuneStrArray::const_iterator begin, RuneStrArray::const_iterator end, vector<WordRange>& res) const {
47
+ RuneStrArray::const_iterator left = begin;
48
+ RuneStrArray::const_iterator right = begin;
49
+ while (right != end) {
50
+ if (right->rune < 0x80) {
51
+ if (left != right) {
52
+ InternalCut(left, right, res);
53
+ }
54
+ left = right;
55
+ do {
56
+ right = SequentialLetterRule(left, end);
57
+ if (right != left) {
58
+ break;
59
+ }
60
+ right = NumbersRule(left, end);
61
+ if (right != left) {
62
+ break;
63
+ }
64
+ right ++;
65
+ } while (false);
66
+ WordRange wr(left, right - 1);
67
+ res.push_back(wr);
68
+ left = right;
69
+ } else {
70
+ right++;
71
+ }
72
+ }
73
+ if (left != right) {
74
+ InternalCut(left, right, res);
75
+ }
76
+ }
77
+ private:
78
+ // sequential letters rule
79
+ RuneStrArray::const_iterator SequentialLetterRule(RuneStrArray::const_iterator begin, RuneStrArray::const_iterator end) const {
80
+ Rune x = begin->rune;
81
+ if (('a' <= x && x <= 'z') || ('A' <= x && x <= 'Z')) {
82
+ begin ++;
83
+ } else {
84
+ return begin;
85
+ }
86
+ while (begin != end) {
87
+ x = begin->rune;
88
+ if (('a' <= x && x <= 'z') || ('A' <= x && x <= 'Z') || ('0' <= x && x <= '9')) {
89
+ begin ++;
90
+ } else {
91
+ break;
92
+ }
93
+ }
94
+ return begin;
95
+ }
96
+ //
97
+ RuneStrArray::const_iterator NumbersRule(RuneStrArray::const_iterator begin, RuneStrArray::const_iterator end) const {
98
+ Rune x = begin->rune;
99
+ if ('0' <= x && x <= '9') {
100
+ begin ++;
101
+ } else {
102
+ return begin;
103
+ }
104
+ while (begin != end) {
105
+ x = begin->rune;
106
+ if ( ('0' <= x && x <= '9') || x == '.') {
107
+ begin++;
108
+ } else {
109
+ break;
110
+ }
111
+ }
112
+ return begin;
113
+ }
114
+ void InternalCut(RuneStrArray::const_iterator begin, RuneStrArray::const_iterator end, vector<WordRange>& res) const {
115
+ vector<size_t> status;
116
+ Viterbi(begin, end, status);
117
+
118
+ RuneStrArray::const_iterator left = begin;
119
+ RuneStrArray::const_iterator right;
120
+ for (size_t i = 0; i < status.size(); i++) {
121
+ if (status[i] % 2) { //if (HMMModel::E == status[i] || HMMModel::S == status[i])
122
+ right = begin + i + 1;
123
+ WordRange wr(left, right - 1);
124
+ res.push_back(wr);
125
+ left = right;
126
+ }
127
+ }
128
+ }
129
+
130
+ void Viterbi(RuneStrArray::const_iterator begin,
131
+ RuneStrArray::const_iterator end,
132
+ vector<size_t>& status) const {
133
+ size_t Y = HMMModel::STATUS_SUM;
134
+ size_t X = end - begin;
135
+
136
+ size_t XYSize = X * Y;
137
+ size_t now, old, stat;
138
+ double tmp, endE, endS;
139
+
140
+ vector<int> path(XYSize);
141
+ vector<double> weight(XYSize);
142
+
143
+ //start
144
+ for (size_t y = 0; y < Y; y++) {
145
+ weight[0 + y * X] = model_->startProb[y] + model_->GetEmitProb(model_->emitProbVec[y], begin->rune, MIN_DOUBLE);
146
+ path[0 + y * X] = -1;
147
+ }
148
+
149
+ double emitProb;
150
+
151
+ for (size_t x = 1; x < X; x++) {
152
+ for (size_t y = 0; y < Y; y++) {
153
+ now = x + y*X;
154
+ weight[now] = MIN_DOUBLE;
155
+ path[now] = HMMModel::E; // warning
156
+ emitProb = model_->GetEmitProb(model_->emitProbVec[y], (begin+x)->rune, MIN_DOUBLE);
157
+ for (size_t preY = 0; preY < Y; preY++) {
158
+ old = x - 1 + preY * X;
159
+ tmp = weight[old] + model_->transProb[preY][y] + emitProb;
160
+ if (tmp > weight[now]) {
161
+ weight[now] = tmp;
162
+ path[now] = preY;
163
+ }
164
+ }
165
+ }
166
+ }
167
+
168
+ endE = weight[X-1+HMMModel::E*X];
169
+ endS = weight[X-1+HMMModel::S*X];
170
+ stat = 0;
171
+ if (endE >= endS) {
172
+ stat = HMMModel::E;
173
+ } else {
174
+ stat = HMMModel::S;
175
+ }
176
+
177
+ status.resize(X);
178
+ for (int x = X -1 ; x >= 0; x--) {
179
+ status[x] = stat;
180
+ stat = path[x + stat*X];
181
+ }
182
+ }
183
+
184
+ const HMMModel* model_;
185
+ bool isNeedDestroy_;
186
+ }; // class HMMSegment
187
+
188
+ } // namespace cppjieba
189
+
190
+ #endif