forked from xtaci/gosegment
/
segment.go
374 lines (332 loc) · 9.6 KB
/
segment.go
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package gosegment
import (
"container/list"
"github.com/xtaci/gosegment/dict"
"github.com/xtaci/gosegment/framework"
"github.com/xtaci/gosegment/match"
"github.com/xtaci/gosegment/utils"
"regexp"
"strings"
"unicode"
)
const PATTERNS = `([0-9\d]+)|([a-zA-Za-zA-Z_]+)`
type Segment struct {
options *match.MatchOptions
params *match.MatchParameter
verbTable map[string]string
wordDictionary *dict.WordDictionary
chsName *dict.ChsName
stopWord *dict.StopWord
synonym *dict.Synonym
re *regexp.Regexp
}
func NewSegment() *Segment {
return &Segment{}
}
func (s *Segment) Init(dictPath string) (err error) {
s.re = regexp.MustCompile(PATTERNS)
err = s.loadVerbTable(dictPath + "/Verbtable.txt")
if err == nil {
err = s.loadDictionary(dictPath)
}
return
}
func (s *Segment) loadVerbTable(file string) (err error) {
s.verbTable = make(map[string]string)
err = utils.EachLine(file, func(line string) {
words := strings.Split(line, "\t")
if len(words) == 3 {
value := strings.TrimSpace(strings.ToLower(words[0]))
for j := 1; j < 3; j++ {
key := strings.TrimSpace(strings.ToLower(words[j]))
s.verbTable[key] = value
}
}
})
return
}
func (s *Segment) loadDictionary(dictPath string) (err error) {
s.wordDictionary = dict.NewWordDictionary()
err = s.wordDictionary.Load(dictPath + "/Dict.txt")
if err == nil {
s.chsName = dict.NewChsName()
s.wordDictionary.ChineseName = s.chsName
err = s.chsName.Load(dictPath)
}
if err == nil {
s.stopWord = dict.NewStopWord()
err = s.stopWord.Load(dictPath + "/Stopword.txt")
}
if err == nil {
s.synonym = dict.NewSynonym()
err = s.synonym.Load(dictPath)
}
// todo: wildchar & segment cross referrence problem
return
}
func (s *Segment) DoSegment(text string) *list.List {
return s.DoSegmentWithOptionParam(text, nil, nil)
}
func (s *Segment) DoSegmentWithOption(text string, params *match.MatchOptions) *list.List {
return s.DoSegmentWithOptionParam(text, params, nil)
}
func (s *Segment) DoSegmentWithOptionParam(text string, options *match.MatchOptions, params *match.MatchParameter) *list.List {
if len(text) == 0 {
return list.New()
}
s.options = options
s.params = params
if s.options == nil {
s.options = match.NewMatchOptions()
}
if s.params == nil {
s.params = match.NewMatchParameter()
}
result := s.preSegment(text)
if s.options.FilterStopWords {
s.filterStopWord(result)
}
s.processAfterSegment(text, result)
return result
}
func (s *Segment) preSegment(text string) *list.List {
result := s.getInitSegment(text)
runes := utils.ToRunes(text)
cur := result.Front()
for cur != nil {
if s.options.IgnoreSpace {
if cur.Value.(*dict.WordInfo).WordType == dict.TSpace {
lst := cur
cur = cur.Next()
result.Remove(lst)
continue
}
}
switch cur.Value.(*dict.WordInfo).WordType {
case dict.TSimplifiedChinese:
inputText := cur.Value.(*dict.WordInfo).Word
originalWordType := dict.TSimplifiedChinese
pls := s.wordDictionary.GetAllMatchs(inputText, s.options.ChineseNameIdentify)
chsMatch := match.NewChsFullTextMatch(s.wordDictionary)
chsMatch.SetOptionParams(s.options, s.params)
chsMatchWords := chsMatch.Match(pls, inputText)
curChsMatch := chsMatchWords.Front()
for curChsMatch != nil {
wi := curChsMatch.Value.(*dict.WordInfo)
wi.Position += cur.Value.(*dict.WordInfo).Position
wi.OriginalWordType = originalWordType
wi.WordType = originalWordType
curChsMatch = curChsMatch.Next()
}
rcur := utils.InsertAfterList(result, chsMatchWords, cur)
removeItem := cur
cur = rcur.Next()
result.Remove(removeItem)
case dict.TEnglish:
cur.Value.(*dict.WordInfo).Rank = s.params.EnglishRank
cur.Value.(*dict.WordInfo).Word = s.convertChineseCapicalToAsiic(cur.Value.(*dict.WordInfo).Word)
if s.options.IgnoreCapital {
cur.Value.(*dict.WordInfo).Word = strings.ToLower(cur.Value.(*dict.WordInfo).Word)
}
if s.options.EnglishSegment {
lower := strings.ToLower(cur.Value.(*dict.WordInfo).Word)
if lower != cur.Value.(*dict.WordInfo).Word {
result.InsertBefore(dict.NewWordInfo(lower, cur.Value.(*dict.WordInfo).Position, dict.POS_A_NX, 1, s.params.EnglishLowerRank, dict.TEnglish, dict.TEnglish), cur)
}
stem := s.getStem(lower)
if len(stem) > 0 {
if lower != stem {
result.InsertBefore(dict.NewWordInfo(stem, cur.Value.(*dict.WordInfo).Position, dict.POS_A_NX, 1, s.params.EnglishStemRank, dict.TEnglish, dict.TEnglish), cur)
}
}
}
if s.options.EnglishMultiDimensionality {
needSplit := false
for _, c := range cur.Value.(*dict.WordInfo).Word {
if (c >= '0' && c <= '9') || (c == '_') {
needSplit = true
break
}
}
if needSplit {
output := s.re.FindAllString(cur.Value.(*dict.WordInfo).Word, -1)
if len(output) > 1 {
position := cur.Value.(*dict.WordInfo).Position
for _, splitWord := range output {
if len(splitWord) == 0 {
continue
}
var wi *dict.WordInfo
r := utils.FirstRune(splitWord)
if r >= '0' && r <= '9' {
wi = dict.NewWordInfoSome(splitWord, dict.POS_A_M, 1)
wi.Position = position
wi.Rank = s.params.NumericRank
wi.OriginalWordType = dict.TEnglish
wi.WordType = dict.TNumeric
} else {
wi = dict.NewWordInfoSome(splitWord, dict.POS_A_NX, 1)
wi.Position = position
wi.Rank = s.params.EnglishRank
wi.OriginalWordType = dict.TEnglish
wi.WordType = dict.TEnglish
}
result.InsertBefore(wi, cur)
position += utils.RuneLen(splitWord)
}
}
}
}
var ok bool
if ok, cur = s.mergeEnglishSpecialWord(runes, result, cur); !ok {
cur = cur.Next()
}
case dict.TNumeric:
cur.Value.(*dict.WordInfo).Word = s.convertChineseCapicalToAsiic(cur.Value.(*dict.WordInfo).Word)
cur.Value.(*dict.WordInfo).Rank = s.params.NumericRank
var ok bool
if ok, cur = s.mergeEnglishSpecialWord(runes, result, cur); !ok {
cur = cur.Next()
}
case dict.TSymbol:
cur.Value.(*dict.WordInfo).Rank = s.params.SymbolRank
cur = cur.Next()
default:
cur = cur.Next()
}
}
return result
}
func (s *Segment) getStem(word string) string {
if stem, ok := s.verbTable[word]; ok {
return stem
}
st := framework.NewStemmer()
for _, r := range word {
if unicode.IsLetter(r) {
st.Add(r)
}
}
st.Stem()
return st.ToString()
}
func (s *Segment) mergeEnglishSpecialWord(orginalText []rune, wordInfoList *list.List, current *list.Element) (bool, *list.Element) {
cur := current
cur = cur.Next()
last := -1
for cur != nil {
if cur.Value.(*dict.WordInfo).WordType == dict.TSymbol || cur.Value.(*dict.WordInfo).WordType == dict.TEnglish {
last = cur.Value.(*dict.WordInfo).Position + utils.RuneLen(cur.Value.(*dict.WordInfo).Word)
cur = cur.Next()
} else {
break
}
}
if last >= 0 {
first := current.Value.(*dict.WordInfo).Position
newWord := orginalText[first:last]
wa := s.wordDictionary.GetWordAttr(newWord)
if wa == nil {
return false, current
}
for current != cur {
removeItem := current
current = current.Next()
wordInfoList.Remove(removeItem)
}
wi := dict.NewWordInfoDefault()
wi.Word = string(newWord)
wi.Pos = wa.Pos
wi.Frequency = wa.Frequency
wi.WordType = dict.TEnglish
wi.Position = first
wi.Rank = s.params.EnglishRank
if current == nil {
wordInfoList.PushBack(wi)
} else {
wordInfoList.InsertBefore(wi, current)
}
return true, current
}
return false, current
}
func (s *Segment) convertChineseCapicalToAsiic(text string) string {
runes := utils.ToRunes(text)
for i := 0; i < len(runes); i++ {
if runes[i] >= '0' && runes[i] <= '9' {
runes[i] -= '0'
runes[i] += '0'
} else if runes[i] >= 'a' && runes[i] <= 'z' {
runes[i] -= 'a'
runes[i] += 'a'
} else if runes[i] >= 'A' && runes[i] <= 'Z' {
runes[i] -= 'A'
runes[i] += 'A'
}
}
return string(runes)
}
func (s *Segment) getInitSegment(text string) *list.List {
result := list.New()
runes := utils.ToRunes(text)
lexical := framework.NewLexical(runes)
var dfaResult int
for i := 0; i < len(runes); i++ {
dfaResult = lexical.Input(runes[i], i)
switch dfaResult {
case framework.Continue:
continue
case framework.Quit:
result.PushBack(lexical.OutputToken)
case framework.ElseQuit:
result.PushBack(lexical.OutputToken)
if lexical.OldState != 255 {
i--
}
}
}
dfaResult = lexical.Input(0, len(runes))
switch dfaResult {
case framework.Continue:
case framework.Quit:
result.PushBack(lexical.OutputToken)
case framework.ElseQuit:
result.PushBack(lexical.OutputToken)
}
return result
}
func (s *Segment) filterStopWord(wordInfoList *list.List) {
if wordInfoList == nil {
return
}
cur := wordInfoList.Front()
for cur != nil {
if s.stopWord.IsStopWord(cur.Value.(*dict.WordInfo).Word, s.options.FilterEnglish, s.params.FilterEnglishLength, s.options.FilterNumeric, s.params.FilterNumericLength) {
remoteItem := cur
cur = cur.Next()
wordInfoList.Remove(remoteItem)
} else {
cur = cur.Next()
}
}
}
func (s *Segment) processAfterSegment(text string, result *list.List) {
// 匹配同义词
if s.options.SynonymOutput {
node := result.Front()
for node != nil {
pW := node.Value.(*dict.WordInfo)
synonyms := s.synonym.GetSynonyms(pW.Word)
if synonyms != nil {
for _, word := range synonyms {
node = result.InsertAfter(dict.NewWordInfo(word, pW.Position, pW.Pos, pW.Frequency, s.params.SymbolRank, dict.TSynonym, pW.WordType), node)
}
}
node = node.Next()
}
}
// 通配符匹配
if s.options.WildcardOutput {
// todo: >>>>>>>
}
}