|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +type cmdArgs struct { |
| 13 | + inputFile string |
| 14 | + outputFile string |
| 15 | +} |
| 16 | + |
| 17 | +func genCode(inFile *os.File, outFile *os.File) { |
| 18 | + rd := bufio.NewReader(inFile) |
| 19 | + output := `package pinyin |
| 20 | +
|
| 21 | +// phraseDict is data map |
| 22 | +// |
| 23 | +// Generate from: |
| 24 | +// https://github.com/hotoo/pinyin/blob/master/data/phrases-dict.js |
| 25 | +// |
| 26 | +// Warning: Auto-generated file, don't edit. |
| 27 | +// If you want add more words, use phrase_dict_addition.go |
| 28 | +var phraseDict = map[string]string{ |
| 29 | +` |
| 30 | + lines := []string{} |
| 31 | + |
| 32 | + for { |
| 33 | + line, err := rd.ReadString('\n') |
| 34 | + if err == io.EOF { |
| 35 | + break |
| 36 | + } else if err != nil { |
| 37 | + panic(err) |
| 38 | + } |
| 39 | + |
| 40 | + // Remove prefix space |
| 41 | + line = strings.TrimSpace(line) |
| 42 | + |
| 43 | + // `"后来居上": [["hòu"], ["lái"], ["jū"], ["shàng"]],` to `"后来居上": "hòu lái jū shàng",` |
| 44 | + if !strings.HasPrefix(line, `"`) { |
| 45 | + continue |
| 46 | + } |
| 47 | + |
| 48 | + line = strings.ReplaceAll(line, `[`, "") |
| 49 | + line = strings.ReplaceAll(line, `]`, "") |
| 50 | + line = strings.ReplaceAll(line, `", "`, " ") |
| 51 | + |
| 52 | + lines = append(lines, line) |
| 53 | + } |
| 54 | + |
| 55 | + output += strings.Join(lines, "\n") |
| 56 | + output += "\n}\n" |
| 57 | + outFile.WriteString(output) |
| 58 | + return |
| 59 | +} |
| 60 | + |
| 61 | +func parseCmdArgs() cmdArgs { |
| 62 | + flag.Parse() |
| 63 | + inputFile := flag.Arg(0) |
| 64 | + outputFile := flag.Arg(1) |
| 65 | + return cmdArgs{inputFile, outputFile} |
| 66 | +} |
| 67 | + |
| 68 | +func main() { |
| 69 | + args := parseCmdArgs() |
| 70 | + usage := "gen_phrase_dict INPUT OUTPUT" |
| 71 | + inputFile := args.inputFile |
| 72 | + outputFile := args.outputFile |
| 73 | + if inputFile == "" || outputFile == "" { |
| 74 | + fmt.Println(usage) |
| 75 | + os.Exit(1) |
| 76 | + } |
| 77 | + |
| 78 | + inFp, err := os.Open(inputFile) |
| 79 | + if err != nil { |
| 80 | + fmt.Printf("open file %s error", inputFile) |
| 81 | + panic(err) |
| 82 | + } |
| 83 | + outFp, err := os.Create(outputFile) |
| 84 | + if err != nil { |
| 85 | + fmt.Printf("open file %s error", outputFile) |
| 86 | + panic(err) |
| 87 | + } |
| 88 | + defer inFp.Close() |
| 89 | + defer outFp.Close() |
| 90 | + |
| 91 | + genCode(inFp, outFp) |
| 92 | +} |
0 commit comments