![](/img/trans.png)
[英]Use PYCOUNTRY to convert ISO 3166-1 alpha-2 to Country Name
[英]How do I get the country name based on the ISO-3166-1 alpha-2 code?
我想從 python 中的變量翻譯文本。
country = input(" Please choose a contry tagg (like fr, us...) :")
我想翻譯文本用戶輸入,例如:
fr = France
us = USA
https://laendercode.net/fr/2-letter-list.html
我想把它翻譯成有效的國家,比如:法國、美國等。
我怎樣才能做到這一點?
您可以嘗試模塊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
有關更多信息,請參閱此
這被稱為“國際化”,用於執行此操作的 Python 模塊是gettext 。 例如:
為了為 I18N 准備代碼,您需要查看文件中的所有字符串。 任何需要翻譯的字符串都應通過將其包裝在 _('...') 中進行標記——即調用 function _()。 例如:
filename = 'mylog.txt'
message = _('writing a log message')
with open(filename, 'w') as fp:
fp.write(message)
這是一個復雜的主題,該頁面將為您提供大量信息。
您可以使用country_converter
,安裝pip install country_converter
。
與pycountry
大約 10mb 相比,這大約是 50kb。
轉換很容易,例如:
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
可以是單數或可以混合輸入的列表
names="fr"
names=["fr", "USA", "826", 276, "China"]
文檔中列出了許多分類方案,可以作為輸入或轉換為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.