将 ISO 639-1 转换为 ISO 639-2

Convert ISO 639-1 to ISO 639-2

我需要拿一个ISO 639-1 code such as en-GB and convert it into an ISO 639-2 code,比如eng

我查看了以下库,但没有找到在其中任何一个中执行该转换的记录方法:

我错过了什么吗?也就是说 - 这些库中的任何一个都可能吗?

维基百科的

List of ISO 639-2 codes 有一个 table 指定对应关系。由于它不是 1-1 映射,因此转换并不总是可行的。

确实遗漏了一些东西 - 很有可能使用您指定的库进行转换。

Built-in language converters (alpha2, alpha3b, alpha3t, name, scope, type and opensubtitles):

>>> language = babelfish.Language('por', 'BR')
>>> language.alpha2
'pt'
<...>
>>> babelfish.Language.fromalpha3b('fre')
<Language [fr]>
  • langcodes 是为不同的任务量身定制的——识别和匹配语言而不考虑标准。因此,您可以提取与初始代码相关的所有代码 - 在不同程度上 - 但它不会告诉您它们属于哪些标准。

  • pycountry 类似于 babelfish 并被 覆盖。

您可以根据需要使用 pycountry。请注意,如果您想要相反的场景(ISO 639-2 到 ISO 639-1),它可能并不总是有效,因为虽然应该始终存在从 ISO 639-1 语言代码到 ISO 639-2 的映射,但相反的是不保证。

import pycountry

code = 'en-GB'

# ISO 639-1 codes are always 2-letter codes, so you have to take
# the first two characters of the code

# This is a safer way to extract the country code from something
# like en-GB (thanks ivan_pozdeev)
lang_code = code[:code.index('-')] if '-' in code else code

lang = pycountry.languages.get(iso639_1_code=lang_code)
print("ISO 639-1 code: " + lang.iso639_1_code)
print("ISO 639-2 code: " + lang.iso639_2T_code)
print("ISO 639-3 code: " + lang.iso639_3_code)

以上应该打印出来:

ISO 639-1 code: en
ISO 639-2 code: eng
ISO 639-3 code: eng