go-examples/file-wordcount/main.go

47 lines
865 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 := s.Text()
word = strings.ToLower(word)
word = strings.Replace(word, ".", "", -1)
word = strings.Replace(word, ",", "", -1)
word = strings.Replace(word, "\"", "", -1)
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])
words := wc(f)
if len(os.Args) > 2 {
for i := 2; i < len(os.Args); i++ {
word := strings.ToLower(os.Args[i])
fmt.Println(word, words[word])
}
} else {
fmt.Println(words)
}
}