-
Notifications
You must be signed in to change notification settings - Fork 0
/
word_clozer.go
63 lines (59 loc) · 1.13 KB
/
word_clozer.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
package main
import (
"errors"
"io"
)
type wordClozer struct{}
func (cc *wordClozer) Cloze(rc io.ReadCloser, opts ...clozeOpt) (string, error) {
defer rc.Close()
bs, err := io.ReadAll(rc)
if err != nil {
return "", err
}
if len(bs) == 0 {
return "", errors.New("empty text")
}
r1 := clozeWord(bs, false)
r2 := clozeWord(bs, true)
return r1 + "\n" + r2, nil
}
func clozeWord(bs []byte, toggleCloze bool) string {
var idx int
var result []byte
for idx < len(bs) {
// 跳过开头连续的空格。
if len(result) == 0 && bs[idx] == ' ' {
idx++
continue
}
// 非字母原样放回。
for idx < len(bs) {
if !isLetter(bs[idx]) {
result = append(result, bs[idx])
idx++
continue
}
break
}
// 找到下一个单词。
var word []byte
for idx < len(bs) {
if !isLetter(bs[idx]) {
break
}
word = append(word, bs[idx])
idx++
}
// 遍历到最后。
if len(word) == 0 {
break
}
if toggleCloze {
word = append([]byte("{{c1::"), word...)
word = append(word, []byte("}}")...)
}
result = append(result, word...)
toggleCloze = !toggleCloze
}
return string(result)
}