day18.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. func getTokens(line string) ([]rune, error) {
  10. scanner := bufio.NewScanner(strings.NewReader(line))
  11. scanner.Split(bufio.ScanWords)
  12. var tokens []rune
  13. for scanner.Scan() {
  14. newTokens := []rune(scanner.Text())
  15. tokens = append(tokens, newTokens...)
  16. }
  17. if err := scanner.Err(); err != nil {
  18. return tokens, fmt.Errorf("Scanner error: %s", err)
  19. }
  20. return tokens, nil
  21. }
  22. func readFile(file *os.File) {
  23. scanner := bufio.NewScanner(file)
  24. for scanner.Scan() {
  25. line := scanner.Text()
  26. if line == "" {
  27. continue
  28. }
  29. tokens, err := getTokens(line)
  30. if err != nil {
  31. log.Fatalf("Error scanning %s: %s", line, err)
  32. }
  33. for _, token := range tokens {
  34. fmt.Print(string(token), ",")
  35. }
  36. fmt.Println()
  37. }
  38. if err := scanner.Err(); err != nil {
  39. log.Fatalf("Scanner error: %s", err)
  40. }
  41. }
  42. func main() {
  43. if len(os.Args) < 2 {
  44. log.Fatal("You need to specify a file!")
  45. }
  46. filePath := os.Args[1]
  47. file, err := os.Open(filePath)
  48. if err != nil {
  49. log.Fatalf("Failed to open %s!\n", filePath)
  50. }
  51. readFile(file)
  52. if err := file.Close(); err != nil {
  53. log.Fatalf("Failed to close file: %s", err)
  54. }
  55. }