2016-11-16 190 views
0

我试图将国家/地区名称转换为所需的国家/地区代码。从用户输入中使用pycountry获取国家代码

例如:

United Kingdom : UK 

我已经尝试以下操作:

import pycountry 
user_input = raw_input(': ') 
mapping = {country.name: country.alpha2 for country in pycountry.countries} 
print mapping.get(user_input) 

我相信我可能误解了的文档,因为我收到以下错误:

mapping = {country.name: country.alpha2 for country in pycountry.countries} 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pycountry/db.py", line 22, in __getattr__ 
    raise AttributeError 
AttributeError 
+3

应该是'country.alpha_2'而不是'country.alpha2'。 – acw1668

回答

2
import pycountry 
user_input = raw_input(': ') 
mapping = {country.name: country.alpha_2 for country in pycountry.countries} 
print mapping.get(user_input) 

是修正t您使用'alpha2'而不是alpha_2的方式

+1

请在处理新模块时始终使用dir() –