
本文旨在提供一个清晰且实用的指南,帮助读者使用 Python 编写函数来查找给定国家名称的 2 位和 3 位 ISO 国家代码。通过加载包含国家信息的 JSON 文件,并进行精确匹配,该函数能够准确地返回所需的 ISO 代码,并处理未找到国家的情况。
以下是如何使用 Python 实现 lookup_country_iso_codes 函数,该函数接受国家名称作为输入,并返回其对应的 2 位和 3 位 ISO 代码:
import json
def lookup_country_iso_codes(country: str) -> tuple:
"""
根据国家名称,从 countries.json 文件中查找并返回 2 位和 3 位 ISO 国家代码。
如果未找到该国家,则返回 (None, None)。
Args:
country (str): 要查找的国家名称。
Returns:
tuple: 包含 2 位和 3 位 ISO 代码的元组。如果未找到国家,则返回 (None, None)。
"""
try:
with open('countries.json', 'r', encoding='utf-8') as file:
countries = json.load(file)
except FileNotFoundError:
print("错误:找不到 'countries.json' 文件。请确保该文件位于当前工作目录中。")
return None, None
except json.JSONDecodeError:
print("错误:'countries.json' 文件格式无效。请检查 JSON 格式是否正确。")
return None, None
for c in countries:
if c['name'] == country:
return c['iso2'], c['iso3']
return None, None
# 示例用法
print(lookup_country_iso_codes("Taiwan"))
print(lookup_country_iso_codes("Japan"))
print(lookup_country_iso_codes("United States"))
print(lookup_country_iso_codes("NonExistentCountry"))代码解释:
countries.json 文件应包含一个 JSON 数组,其中每个元素代表一个国家,并且至少包含 name、iso2 和 iso3 键。例如:
立即学习“Python免费学习笔记(深入)”;
[
{
"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"
}
]通过这个教程,你已经学会了如何使用 Python 创建一个函数,根据国家名称查找其对应的 2 位和 3 位 ISO 代码。 这个函数对于需要处理国家信息的应用程序非常有用。 记住要验证 countries.json 文件的路径和内容,并考虑添加额外的错误处理以提高代码的可靠性。
以上就是使用 Python 查询国家 ISO 代码:一个教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号