How do I convert a language code to its proper name in Go?

huangapple go评论85阅读模式
英文:

How do I convert a language code to its proper name in Go?

问题

你可以使用语言代码和名称之间的映射表来进行转换。以下是一个示例代码,可以将语言代码转换为对应的语言名称:

language_map = {
    'en-US': 'American English',
    'ja': 'Japanese',
    # 添加更多的语言代码和名称
}

def convert_language_code(code):
    if code in language_map:
        return language_map[code]
    else:
        return 'Unknown'

# 示例用法
code = 'en-US'
language_name = convert_language_code(code)
print(language_name)  # 输出:American English

你可以根据需要扩展language_map字典,添加更多的语言代码和对应的语言名称。然后,使用convert_language_code函数将语言代码转换为对应的语言名称。如果给定的语言代码在映射表中不存在,函数将返回"Unknown"。

英文:

I need to convert language codes like 'en-US' or 'ja' to their proper names like 'American English' and 'Japanese'. How do I do this?

答案1

得分: 4

我在查找这个功能时遇到了一些困难,因为它分散在两个不同的包中——languagesdisplay,而不是在一个包中。希望这对那些找不到如何做到这一点的人有所帮助。

文档链接:
https://pkg.go.dev/golang.org/x/text/language#CanonType.MustParse
https://pkg.go.dev/golang.org/x/text@v0.3.7/language/display#Namer

示例程序:

package main

import (
	"fmt"
	"golang.org/x/text/language"
	"golang.org/x/text/language/display"
)

func main()  {
	japTag := language.MustParse("ja")
	fmt.Println(display.Self.Name(japTag))   // --> 日本語

    // 获取英文的语言名称
    en := display.English.Languages()
    fmt.Println(en.Name(japTag))             // --> Japanese
}
英文:

I had some difficulty in finding this since the functionality is spread across 2 different packages - languages and display instead of being in one. Hope this helps someone who couldn't find out how to do this.

links to documentation:
https://pkg.go.dev/golang.org/x/text/language#CanonType.MustParse
https://pkg.go.dev/golang.org/x/text@v0.3.7/language/display#Namer

Sample Program:

package main

import (
	"fmt"
	"golang.org/x/text/language"
	"golang.org/x/text/language/display"
)

func main()  {
	japTag := language.MustParse("ja")
	fmt.Println(display.Self.Name(japTag))   // --> 日本語

    // To get the language names in English
    en := display.English.Languages()
    fmt.Println(en.Name(japTag))             // --> Japanese
}

huangapple
  • 本文由 发表于 2021年10月5日 14:14:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/69445633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定