gen_pinyin_dict.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package main
  2. import (
  3. "bufio"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "os"
  8. "strings"
  9. )
  10. type cmdArgs struct {
  11. inputFile string
  12. outputFile string
  13. }
  14. func genCode(inFile *os.File, outFile *os.File) {
  15. rd := bufio.NewReader(inFile)
  16. output := `package pinyin
  17. // PinyinDict is data map
  18. // Warning: Auto-generated file, don't edit.
  19. var PinyinDict = map[int]string{
  20. `
  21. lines := []string{}
  22. for {
  23. line, err := rd.ReadString('\n')
  24. if err == io.EOF {
  25. break
  26. } else if err != nil {
  27. panic(err)
  28. }
  29. if strings.HasPrefix(line, "#") {
  30. continue
  31. }
  32. // line: `U+4E2D: zhōng,zhòng # 中`
  33. dataSlice := strings.Split(line, " #")
  34. dataSlice = strings.Split(dataSlice[0], ": ")
  35. // 0x4E2D
  36. hexCode := strings.Replace(dataSlice[0], "U+", "0x", 1)
  37. // zhōng,zhòng
  38. pinyin := dataSlice[1]
  39. lines = append(lines, fmt.Sprintf("\t%s: \"%s\",", hexCode, pinyin))
  40. }
  41. output += strings.Join(lines, "\n")
  42. output += "\n}\n"
  43. outFile.WriteString(output)
  44. return
  45. }
  46. func parseCmdArgs() cmdArgs {
  47. flag.Parse()
  48. inputFile := flag.Arg(0)
  49. outputFile := flag.Arg(1)
  50. return cmdArgs{inputFile, outputFile}
  51. }
  52. func main() {
  53. args := parseCmdArgs()
  54. usage := "gen_pinyin_dict INPUT OUTPUT"
  55. inputFile := args.inputFile
  56. outputFile := args.outputFile
  57. if inputFile == "" || outputFile == "" {
  58. fmt.Println(usage)
  59. os.Exit(1)
  60. }
  61. inFp, err := os.Open(inputFile)
  62. if err != nil {
  63. fmt.Printf("open file %s error", inputFile)
  64. panic(err)
  65. }
  66. outFp, err := os.Create(outputFile)
  67. if err != nil {
  68. fmt.Printf("open file %s error", outputFile)
  69. panic(err)
  70. }
  71. defer inFp.Close()
  72. defer outFp.Close()
  73. genCode(inFp, outFp)
  74. }