在go语言中使用语言包翻译语言的代码示例
一个简单的例子,说明如何使用语言包来做语言翻译。不是google translate类型的翻译引擎....,仍然需要为每个翻译提供精确的匹配才行。
把这个放在这里,供我自己将来参考。
示例代码:
package main
import (
//"fmt" -- 在这个例子中用消息包代替
"golang.org/x/text/language"
"golang.org/x/text/language/display"
"golang.org/x/text/message"
)
func main() {
//定义一个从英语到荷兰语的直接翻译
message.SetString(language.Dutch, "In %v people speak %v.", "In %v spreekt men %v.")
fr := language.French
region, _ := fr.Region()
for _, tag := range []string{"en", "nl"} {
p := message.NewPrinter(language.Make(tag))
p.Printf("In %v people speak %v.", display.Region(region), display.Language(fr))
p.Println()
}
//定义一个直接的英汉翻译
message.SetString(language.Chinese, "In %v people speak %v.", "在%v说%v.") // * 必须与翻译相匹配,才能发挥作用
zh := language.Chinese
region, _ = zh.Region()
for _, tag := range []string{"en", "zh"} {
p := message.NewPrinter(language.Make(tag))
p.Printf("In %v people speak %v.", display.Region(region), display.Language(zh)) // *必须匹配的翻译才能发挥作用
p.Println()
}
//定义从英语到马来语的直接翻译
message.SetString(language.Malay, "In %v people speak %v.", "Orang %v berbahasa %v.")
msmy := language.Malay
region, _ = msmy.Region()
for _, tag := range []string{"en", "ms"} {
p := message.NewPrinter(language.Make(tag))
p.Printf("In %v people speak %v.", display.Region(region), display.Language(msmy))
p.Println()
}
}
输出:
In France people speak French.
In Frankrijk spreekt men Frans.
In China people speak Chinese.
在中国说中文.
In Malaysia people speak Malay.
Orang Malaysia berbahasa Melayu.
相关链接:
https://godoc.org/golang.org/x/text/message
https://godoc.org/golang.org/x/text/language/display#Dictionary.Languages
相关文章