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

sam*_*per 2 python iso-639

我需要采用ISO 639-1代码en-GB然后将其转换为ISO 639-2代码,例如eng

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

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

wkl*_*wkl 5

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

上面应该打印出来:

ISO 639-1 code: en
ISO 639-2 code: eng
ISO 639-3 code: eng
Run Code Online (Sandbox Code Playgroud)