简体   繁体   中英

How do I get the country name based on the ISO-3166-1 alpha-2 code?

I want to translate text from variable in python.

country = input(" Please choose a contry tagg (like fr, us...) :")

I want to translate the text user input such as:

fr = France
us = USA

https://laendercode.net/fr/2-letter-list.html

And I want to translate this into the valid country like: France, USA, etc.

How can I do this?

You can try the module pycountry , in the command line run pip install pycountry , and then in your code:

import pycountry
country_code = input(" Please choose a contry tagg (like fr, us...) :")
country = pycountry.countries.get(alpha_2=country_code)
country_name = country.name

For more info see this

This is referred to as "internationalization", and the Python module for doing this is gettext . For example:

In order to prepare your code for I18N, you need to look at all the strings in your files. Any string that needs to be translated should be marked by wrapping it in _('...') — that is, a call to the function _(). For example:

filename = 'mylog.txt'
message = _('writing a log message')
with open(filename, 'w') as fp:
    fp.write(message)

This is a complex subject and that page will give you a lot of information to start with.

You could use country_converter , install with pip install country_converter .
This is around 50kb compared to pycountry being around 10mb.

Conversion is easy with something like:

import country_converter as coco
input_country = input(" Please choose a contry tagg (like fr, us...) :")
converted_country = coco.convert(names=input_country, to="name")
print(converted_country)
  • names can be singular or a list which can be mixed input
    • names="fr"
    • names=["fr", "USA", "826", 276, "China"]

There are a lot of classification schemes listed in the documentation that can be taken as inputs or converted to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM