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