
本文旨在提供一个清晰、简洁的 Python 函数,用于根据国家名称查找其对应的 2 位和 3 位 ISO 国家代码。通过加载包含国家信息的 JSON 文件,该函数能够高效地检索并返回所需的 ISO 代码,同时处理未找到国家的情况。
以下是一个名为 lookup_country_iso_codes 的 Python 函数,它接收一个国家名称字符串作为输入,并返回一个包含 2 位和 3 位 ISO 国家代码的元组。
import json
def lookup_country_iso_codes(country: str) -> tuple:
# Load the JSON file
with open('countries.json') as file:
countries = json.load(file)
# Iterate through countries and match the specified country name
for c in countries:
if c['name'] == country:
# Return 2-digit and 3-digit ISO codes when a match is found
return c['iso2'], c['iso3']
# If the country is not found, return None for both values
return None, None这段代码首先导入了 json 模块,用于处理 JSON 格式的数据。函数 lookup_country_iso_codes 接收一个字符串参数 country,表示要查找的国家名称。它打开名为 countries.json 的文件,并使用 json.load() 函数将 JSON 数据加载到名为 countries 的变量中。
然后,代码遍历 countries 列表,对每个国家 c 检查其 name 属性是否与输入的 country 匹配。如果找到匹配项,则返回该国家的 iso2 和 iso3 属性,分别代表 2 位和 3 位 ISO 代码。
立即学习“Python免费学习笔记(深入)”;
如果遍历完所有国家后仍未找到匹配项,则函数返回 (None, None),表示未找到该国家。
为了使函数正常工作,countries.json 文件必须包含一个 JSON 数组,其中每个元素都是一个包含国家信息的 JSON 对象。每个对象至少应包含 name、iso2 和 iso3 属性,分别表示国家名称、2 位 ISO 代码和 3 位 ISO 代码。例如:
[
{
"name": "Afghanistan",
"iso2": "AF",
"iso3": "AFG",
"numeric": "004"
},
{
"name": "South Africa",
"iso2": "ZA",
"iso3": "ZAF",
"numeric": "710"
},
{
"name": "Åland Islands",
"iso2": "AX",
"iso3": "ALA",
"numeric": "248"
}
]以下是一些使用 lookup_country_iso_codes 函数的示例:
print(lookup_country_iso_codes("Taiwan")) # 输出: ('TW', 'TWN')
print(lookup_country_iso_codes("Japan")) # 输出: ('JP', 'JPN')
print(lookup_country_iso_codes("United States")) # 输出: ('US', 'USA')
print(lookup_country_iso_codes("NonExistentCountry")) # 输出: (None, None)lookup_country_iso_codes 函数提供了一种简单有效的方法,可以根据国家名称查找其 ISO 代码。通过使用 JSON 文件存储国家信息,该函数具有良好的可扩展性和易用性。使用时请注意数据准确性和文件路径,并根据需要添加适当的错误处理机制。
以上就是使用 Python 查询国家 ISO 代码:一份详细教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号