go-examples/file-wordcount/main.go

47 lines
865 B
Go
Raw Normal View History

2017-07-07 12:29:36 +00:00
package main
import "fmt"
import "io"
import "log"
import "os"
2017-07-07 14:13:45 +00:00
import "bufio"
2017-07-07 12:29:36 +00:00
import "strings"
func wc(r io.Reader) map[string]uint {
words := make(map[string]uint)
2017-07-07 14:13:45 +00:00
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)
2017-07-07 14:13:45 +00:00
words[word]++
2017-07-07 12:29:36 +00:00
}
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)
}
2017-07-07 12:29:36 +00:00
}