| 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 |
// PinyinDict is data map |
| 22 |
// Warning: Auto-generated file, don't edit. |
| 23 |
var PinyinDict = map[int]string{ |
| 24 |
` |
| 25 |
lines := []string{} |
| 26 |
|
| 27 |
for { |
| 28 |
line, err := rd.ReadString('\n') |
| 29 |
if err == io.EOF { |
| 30 |
break |
| 31 |
} else if err != nil { |
| 32 |
panic(err) |
| 33 |
} |
| 34 |
if strings.HasPrefix(line, "#") { |
| 35 |
continue |
| 36 |
} |
| 37 |
|
| 38 |
中` |
| 39 |
dataSlice := strings.Split(line, " #") |
| 40 |
dataSlice = strings.Split(dataSlice[0], ": ") |
| 41 |
|
| 42 |
hexCode := strings.Replace(dataSlice[0], "U+", "0x", 1) |
| 43 |
ng |
| 44 |
pinyin := dataSlice[1] |
| 45 |
lines = append(lines, fmt.Sprintf("\t%s: \"%s\",", hexCode, pinyin)) |
| 46 |
} |
| 47 |
|
| 48 |
output += strings.Join(lines, "\n") |
| 49 |
output += "\n}\n" |
| 50 |
outFile.WriteString(output) |
| 51 |
return |
| 52 |
} |
| 53 |
|
| 54 |
func parseCmdArgs() cmdArgs { |
| 55 |
flag.Parse() |
| 56 |
inputFile := flag.Arg(0) |
| 57 |
outputFile := flag.Arg(1) |
| 58 |
return cmdArgs{inputFile, outputFile} |
| 59 |
} |
| 60 |
|
| 61 |
func main() { |
| 62 |
args := parseCmdArgs() |
| 63 |
usage := "gen_pinyin_dict INPUT OUTPUT" |
| 64 |
inputFile := args.inputFile |
| 65 |
outputFile := args.outputFile |
| 66 |
if inputFile == "" || outputFile == "" { |
| 67 |
fmt.Println(usage) |
| 68 |
os.Exit(1) |
| 69 |
} |
| 70 |
|
| 71 |
inFp, err := os.Open(inputFile) |
| 72 |
if err != nil { |
| 73 |
fmt.Printf("open file %s error", inputFile) |
| 74 |
panic(err) |
| 75 |
} |
| 76 |
outFp, err := os.Create(outputFile) |
| 77 |
if err != nil { |
| 78 |
fmt.Printf("open file %s error", outputFile) |
| 79 |
panic(err) |
| 80 |
} |
| 81 |
defer inFp.Close() |
| 82 |
defer outFp.Close() |
| 83 |
|
| 84 |
genCode(inFp, outFp) |
| 85 |
} |