go-examples/file-wordcount/main.go
2017-07-07 16:13:45 +02:00

35 lines
550 B
Go

package main
import "fmt"
import "io"
import "log"
import "os"
import "bufio"
import "strings"
func wc(r io.Reader) map[string]uint {
words := make(map[string]uint)
s := bufio.NewScanner(r)
s.Split(bufio.ScanWords)
for s.Scan() {
word := strings.ToLower(s.Text())
words[word]++
}
return words
}
func openFile(path *string) *os.File {
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatalln(err)
}
return f
}
func main() {
if len(os.Args) <= 1 {
log.Fatalln("Missing file")
}
f := openFile(&os.Args[1])
fmt.Println(wc(f))
}