-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcount.go
279 lines (249 loc) · 5.94 KB
/
count.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
package main
import (
"container/list"
"flag"
"fmt"
"github.com/kuangcp/gobase/pkg/cuibase"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/go-redis/redis/v7"
)
var fileList = list.New()
var client *redis.Client
func initRedisClient() {
config := readRedisConfig()
if config == nil {
log.Fatal("config error")
}
client = redis.NewClient(config)
}
// 递归遍历目录
func handlerDir(path string, info os.FileInfo, err error) error {
if err != nil {
log.Println("occur error: ", err)
return nil
}
if info.IsDir() {
for _, dir := range ignoreDirs {
if path == dir {
return filepath.SkipDir
}
}
return nil
}
fileList.PushBack(path)
return nil
}
func isNeedHandle(filename string) bool {
for _, fileType := range handleFiles {
if strings.HasSuffix(filename, fileType) {
return true
}
}
return false
}
func readToBytes(fileName string) []byte {
file, err := os.Open(fileName)
if err != nil {
log.Println("error: ", err)
return nil
}
// 延迟关闭文件
defer file.Close()
//读取文件全部内容
content, err := ioutil.ReadAll(file)
if err != nil {
log.Println("occur error: ", err)
return nil
}
return content
}
// increase count in redis
func increaseCharNum(CNChar string) {
result, e := client.ZIncrBy(charRankKey, 1, CNChar).Result()
if e == redis.Nil {
println(result)
}
}
func showChar(CNChar string) {
fmt.Printf(CNChar)
}
// 根据字节流 统计中文字符
func handleFile(fileName string, chineseCharHandler func(string)) int {
bytes := readToBytes(fileName)
var totalChar = 0
var count = 0
temp := [3]byte{}
for _, item := range bytes {
// 首字节 满足 110xxxxx [4e00,9fa5] 字节的头部分别为 0100 1001
if count == 0 && item >= 228 && item <= 233 {
temp[count] = item
count++
continue
}
// 后续字节 满足 10xxxxxx, 不满足就说明不是汉字了
if count != 0 && item >= 128 && item <= 191 {
temp[count] = item
count++
} else {
count = 0
continue
}
// 缓存满了三个字节, 就可以确定为一个汉字了
if count == 3 {
if chineseCharHandler != nil {
chineseCharHandler(string(temp[0:3]))
}
totalChar++
count = 0
}
}
return totalChar
}
func showCharRank(start int64, stop int64) {
result, e := client.ZRevRangeWithScores(charRankKey, start, stop).Result()
if e != nil {
log.Println("error: ", e)
return
}
for _, a := range result {
fmt.Printf("%-6v %s %v \n", a.Score, cuibase.Green.Print("->"), a.Member)
}
}
func countWithRedis() {
// 递归遍历目录 读取所有文件
err := filepath.Walk("./", handlerDir)
if err != nil {
log.Println(err)
}
for e := fileList.Front(); e != nil; e = e.Next() {
fileName := e.Value.(string)
if isNeedHandle(fileName) {
handleFile(fileName, increaseCharNum)
}
}
}
func showChineseChar(perCharHandler func(string), printFileInfo bool) {
totalChineseChar, totalFile := countSummaryResult(perCharHandler, printFileInfo)
if perCharHandler != nil {
fmt.Println()
}
fmt.Printf("%s Total characters: %v%v%v files %v%v%v chars \n",
time.Now().Format("2006-01-02 15:04:05.000"),
cuibase.Yellow, totalFile, cuibase.End,
cuibase.Yellow, totalChineseChar, cuibase.End)
}
func countSummaryResult(perCharHandler func(string), printFileInfo bool) (int, int) {
if printFileInfo {
fmt.Printf("%v%-3v %-5v %-5v %v%v\n", cuibase.Yellow, "No", "Total", "Cur", "File", cuibase.End)
}
err := filepath.Walk("./", handlerDir)
if err != nil {
log.Println(err)
}
var totalChineseChar = 0
var totalFile = 0
for e := fileList.Front(); e != nil; e = e.Next() {
fileName := e.Value.(string)
if !isNeedHandle(fileName) {
continue
}
totalFile++
var total = 0
total = handleFile(fileName, perCharHandler)
totalChineseChar += total
if printFileInfo {
fmt.Printf("%-3v %-5v %s %v \n",
totalFile, totalChineseChar, cuibase.Green.Printf("%-5v", total), fileName)
}
}
return totalChineseChar, totalFile
}
func delRank() {
initRedisClient()
client.Del(charRankKey)
log.Printf("del %v%v%v", cuibase.Green, charRankKey, cuibase.End)
}
func printRank() {
nums := strings.Split(rankPair, ",")
if len(nums) == 1 {
end, err := strconv.ParseInt(nums[0], 10, 64)
cuibase.CheckIfError(err)
endIdx = end
} else if len(nums) == 2 {
start, err1 := strconv.ParseInt(nums[0], 10, 64)
cuibase.CheckIfError(err1)
stop, err2 := strconv.ParseInt(nums[1], 10, 64)
cuibase.CheckIfError(err2)
startIdx = start
endIdx = stop
} else {
fmt.Println("error rank format eg: 1,2")
return
}
initRedisClient()
showCharRank(startIdx, endIdx)
}
func init() {
flag.StringVar(&handleFileSuffix, "S", "", "")
flag.StringVar(&ignoreDir, "D", "", "")
flag.StringVar(&rankPair, "r", "", "")
flag.StringVar(&targetFile, "f", "", "")
}
func main() {
info.Parse()
if help {
info.PrintHelp()
return
}
if delCache {
delRank()
return
}
if handleFileSuffix != "" {
handleFiles = strings.Split(handleFileSuffix, ",")
}
if ignoreDir != "" {
ignoreDirs = strings.Split(handleFileSuffix, ",")
}
if rankPair != "" {
printRank()
return
}
if targetFile != "" {
log.Printf("%vread file: %v, redis key: %v%v\n",
cuibase.Green, targetFile, charRankKey, cuibase.End)
initRedisClient()
handleFile(targetFile, increaseCharNum)
showCharRank(0, 15)
return
}
if allFile {
initRedisClient()
countWithRedis()
showCharRank(0, 15)
return
}
if printAllChar {
showChineseChar(showChar, false)
return
}
if countSummary {
allChChar, totalFile := countSummaryResult(nil, false)
nowStr := time.Now().Format("2006-01-02 15:04:05.000")
fmt.Printf("%s Total characters: %v files %v chars \n", nowStr, totalFile, allChChar)
return
}
if countSummary2 {
allChChar, totalFile := countSummaryResult(nil, false)
nowStr := time.Now().Format("2006-01-02 15:04:05.000")
fmt.Printf("%s Total characters: %v files %v chars %v l/f\n", nowStr, totalFile, allChChar, allChChar/totalFile)
return
}
showChineseChar(nil, true)
}