[英]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.我想从 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 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:您可以尝试模块
pycountry
,在命令行中运行pip install pycountry
,然后在您的代码中:
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
This is referred to as "internationalization", and the Python module for doing this is gettext .这被称为“国际化”,用于执行此操作的 Python 模块是gettext 。 For example:
例如:
In order to prepare your code for I18N, you need to look at all the strings in your files.
为了为 I18N 准备代码,您需要查看文件中的所有字符串。 Any string that needs to be translated should be marked by wrapping it in _('...') — that is, a call to the function _().
任何需要翻译的字符串都应通过将其包装在 _('...') 中进行标记——即调用 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
.您可以使用
country_converter
,安装pip install country_converter
。
This is around 50kb compared to pycountry
being around 10mb.与
pycountry
大约 10mb 相比,这大约是 50kb。
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
可以是单数或可以混合输入的列表
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.文档中列出了许多分类方案,可以作为输入或转换为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.