2016-07-24 285 views
5

我曾與2個python庫:phonenumbers,pycountry。實際上我找不到一個只給出國家代碼並獲得相應國家名稱的方法。從國家代碼在python中獲取國家名稱?

phonenumbers您需要提供完整的數字parse。在pycountry它只是得到國家的ISO。

是否有任何解決方案或方法來給圖書館國家代碼和國名?

+0

想必當你說國家代碼,你的意思是國際長途代碼。這是真的,還是你的意思是ISO 3166-1 alpha-2? – erip

+2

請提供一個[最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) –

+0

看看'phonenumberutils.region_codes_for_country_code' –

回答

15

phonenumbers庫文檔相當不足;相反,他們建議您查看Google單元測試的原始項目,以瞭解功能。

PhoneNumberUtilTest unittests似乎涵蓋您的具體使用情況;使用getRegionCodeForCountryCode() function將電話號碼的國家部分映射到給定區域。還有一個getRegionCodeForNumber() function似乎首先提取解析號碼的國家/地區代碼屬性。

確實,有相應的phonenumbers.phonenumberutil.region_code_for_country_code()phonenumbers.phonenumberutil.region_code_for_number()功能做同樣在Python:

import phonenumbers 
from phonenumbers.phonenumberutil import (
    region_code_for_country_code, 
    region_code_for_number, 
) 

pn = phonenumbers.parse('+442083661177') 
print(region_code_for_country_code(pn.country_code)) 

演示:

>>> import phonenumbers 
>>> from phonenumbers.phonenumberutil import region_code_for_country_code 
>>> from phonenumbers.phonenumberutil import region_code_for_number 
>>> pn = phonenumbers.parse('+442083661177') 
>>> print(region_code_for_country_code(pn.country_code)) 
GB 
>>> print(region_code_for_number(pn)) 
GB 

所得區域碼是一個雙字母ISO代碼,所以你可以直接使用pycountry

>>> import pycountry 
>>> country = pycountry.countries.get(alpha2=region_code_for_number(pn)) 
>>> print(country.name) 
United Kingdom 

注意,.country_code屬性是只是一個整數,所以你可以使用phonenumbers.phonenumberutil.region_code_for_country_code()沒有電話號碼,只是一個國家代碼:

>>> region_code_for_country_code(1) 
'US' 
>>> region_code_for_country_code(44) 
'GB' 
+0

感謝您的時間和答案。正如我在問題中所說的,我只是把國家代碼和國家代碼的數字不同。所以例如我有+1不是完整的數字。我知道如何使用解析函數,但問題是我只有國家代碼。 – ALH

+0

@AlirezaHos:但是'PhoneNumber.country_code'只是一個整數*,這就是'region_code_for_country_code()'所需要的。更新了答案以突出顯示。 –