-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordCount.go
82 lines (69 loc) · 1.56 KB
/
wordCount.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
package main
import (
"bufio"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
)
type WordCount struct {
Word string
Count int
}
func wordCountHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
searchAllWords(w, r)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func searchAllWords(w http.ResponseWriter, r *http.Request) {
files, err := ioutil.ReadDir("./uploads")
if err != nil {
return
}
wordCounts := make(map[string]int)
wg := sync.WaitGroup{}
mu := sync.Mutex{}
for _, file := range files {
if file.IsDir() {
continue
}
wg.Add(1)
go func(filename string) {
defer wg.Done()
path := filepath.Join(filepath.Join("./uploads", filename))
file, err := os.Open(path)
if err != nil {
fmt.Printf("Failed to open file %s: %s\n", path, err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
word := strings.ToLower(scanner.Text())
mu.Lock()
wordCounts[word]++
mu.Unlock()
}
if err := scanner.Err(); err != nil {
fmt.Printf("Error scanning file %s: %s\n", path, err)
}
}(file.Name())
}
wg.Wait()
topWords := make([]WordCount, 0, len(wordCounts))
for word, count := range wordCounts {
topWords = append(topWords, WordCount{Word: word, Count: count})
}
totalWordCount := 0
for _, wordCount := range topWords {
totalWordCount += wordCount.Count
}
message := fmt.Sprintf("Total word count: %d\n", totalWordCount)
fmt.Fprint(w, message)
}