【问题标题】:Trying to understand Golang pluralization试图理解 Golang 多元化
【发布时间】:2018-12-25 23:40:13
【问题描述】:

我试图理解 Go 中的复数形式。文档https://godoc.org/golang.org/x/text/message/catalog#hdr-String_interpolation 中的示例不起作用。方法plural.Select 事件不存在。应该是plural.Selectf。注意末尾的f

message.Set(language.English, "You are %d minute(s) late.",
catalog.Var("minutes", plural.Selectf(1, "one", "minute")),
catalog.String("You are %d ${minutes} late."))
p := message.NewPrinter(language.English)
p.Printf("You are %d minute(s) late.", 5)

我在这里找到了另一个教程https://phraseapp.com/blog/posts/internationalization-i18n-go/。此代码运行良好

message.Set(language.English, "You have %d problem",
    catalog.Var("minutes", plural.Selectf(1, "%d", "one", "minute", "other", "minutes")),
    catalog.String("You are %d ${minutes} late."))
printer := message.NewPrinter(language.English)
printer.Printf("You have %d problem", 1)
printer.Println()
printer.Printf("You have %d problem", 3)
printer.Println()

// result
// You are 1 minute late.
// You are 3 minutes late.

两个示例都使用高级字符串插值。现在我试图理解plural.Selectf。第一个参数1 在做什么?为什么我需要第二个参数%d?剩下的我想我明白了

"one"  : "minute"
"other": "minutes"

我还在catalog.String 中看到了%[1]d。这是做什么的?

非常感谢!我现在超级迷茫。

【问题讨论】:

    标签: go pluralize cldr


    【解决方案1】:

    给你!

    plural.Selectf 的第一个参数是int。所以它可以是任何有效的整数。 第二个参数是string。它应该是一个格式动词,即%d%s%f 第三个参数是一个空接口,可以接收任何类型,即 string、struct、catalog.Message、..

    我们以这个例子为例,

    func main() {
    
        var (
                msg = plural.Selectf(2, "%d",
                    "=10", "%[1]d task and %[2]d processes remaining!", // interface 1
                    "=1", "%[1]d task and %[2]d processes", // interface 2
                    "other", "%d tasks and %d processes!" // interface 3
                )
                key = "%d task - %d process"
                tag = "en"
            )
    
            lTag := language.MustParse(tag)
            message.Set(lTag, key, msg)
    
            p := message.NewPrinter(language.English)
            p.Printf("%d task - %d process", 1, 10)
    
    }
    

    在这里,我们创建了一个语言为英语的NewPrinter,并使用键%d task(s) remaining! 为标签en(英语的短代码)设置了翻译消息。

    p.Printf("%d task - %d process", 1, 3) 行执行时,翻译机制采用第一个参数(格式说明符),即%d task - %d process,并通过与我们为en 标签设置的键进行比较来检查消息。如果找到密钥,则处理消息,即msg

    这里Selectfs 的第一个参数表示从Printf 获取nth(即我们的例子中的第二个)格式动词的值(即%d 的第二个值中的10)并与案例选择器进行比较,即@案例 1(接口 1)中的 987654338@。如果比较成功,则返回处理后的值,即 1 task and 10 processes 在案例 1 中。

    如果Printf 接收到第 2 个 %d 的值而不是 1 和 10,那么它将从案例 3(接口 3)返回值

    还有,

    %[n]d 可以这样使用,

    fmt.Printf("%[2]d %[1]d\n", 11, 22) 并打印 22 11

    希望对你有所帮助。

    【讨论】:

    • 它开始变得有意义了。我仍然不明白plural.Selectf"%d" 的第二个参数。我试过改变它,似乎我可以在那里写任何我想要的东西。我真的写了“任何东西”,它仍然有效。
    • 我知道plural.Selectf 的第二个参数是它只接受%d, %f, %g, %e。如果我们提供的不是这些,那就只是忽略了价值。此格式动词与catalog.Message 类型一起使用。
    猜你喜欢
    • 2015-05-04
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2012-01-04
    相关资源
    最近更新 更多