Skip to content

Instantly share code, notes, and snippets.

@jmoiron

jmoiron/main.go Secret

Last active October 16, 2020 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmoiron/206337cdc62b999d07ebcbef5c0fc58b to your computer and use it in GitHub Desktop.
Save jmoiron/206337cdc62b999d07ebcbef5c0fc58b to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
)
type WordCount struct {
word string
count int
}
func main() {
wordCounts := make(map[string]int)
err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if !info.Mode().IsRegular() {
return nil
}
if !strings.HasSuffix(path, ".txt") {
return nil
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
word := strings.ToLower(scanner.Text())
if len(word) < 2 {
continue
}
wordCounts[word] += 1
}
return scanner.Err()
})
if err != nil {
fmt.Printf("Error: %s\n", err)
return
}
wordArray := make([]WordCount, 0, len(wordCounts))
for word, count := range wordCounts {
wordArray = append(wordArray, WordCount{word: word, count: count})
}
sort.Slice(wordArray, func(i, j int) bool {
return wordArray[i].count > wordArray[j].count
})
for _, wc := range wordArray[:10] {
fmt.Printf("%d %s\n", wc.count, wc.word)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment