mozillazg / go-pinyin

汉字转拼音
https://godoc.org/github.com/mozillazg/go-pinyin
MIT License
1.6k stars 194 forks source link

增加保留字母和数字的选项 #33

Closed molizz closed 6 years ago

molizz commented 6 years ago

因为业务需要, 增加了一个新的选择.

args.KeepSymbol = true

类似:

12Ha«你好吗

上面的字符串将返回: 12Hanihaoma

既: 保留文字中的数字, 字母

coveralls commented 6 years ago

Coverage Status

Coverage decreased (-8.2%) to 91.837% when pulling ae19820e503d9f15c551f33d817f03180d1fa947 on molizz:master into b950aaffc7bf031ae4b8e7759eaff767b32c3214 on mozillazg:master.

mozillazg commented 6 years ago

@molizz Thanks for your PR!

这个需求也可以通过 Fallback 参数实现,不一定要添加新的参数。比如你举的那个例子:

// cat test.go
package main

import (
    "fmt"
    "strings"

    "github.com/mozillazg/go-pinyin"
)

func IsNumberOrLetter(n int32) bool {
    switch {
    case n >= 48 && n <= 57: // 数字
        return true
    case n >= 65 && n <= 90: // 大写字母
        return true
    case n >= 97 && n <= 122: // 小写字母
        return true
    default:
        return false
    }
    return false
}

func main() {
    a := pinyin.NewArgs()
    // 使用 Fallback 参数处理没有拼音的字符
    a.Fallback = func(r rune, a pinyin.Args) []string {
        if IsNumberOrLetter(r) {
            return []string{string(r)}
        }
        return []string{}
    }
    s := "12Ha«你好吗"
    ps := pinyin.LazyPinyin(s, a)
    fmt.Println(strings.Join(ps, ""))
}
$ go run test.go
12Hanihaoma
molizz commented 6 years ago

也可以哦, 那我关了这个pr. 之前没看到还有这么个回调方法