我如何定义一个函数`lookup_country_iso_codes`来返回2位和3位ISO国家代码

问题描述 投票:0回答:1

问题来了:

定义一个函数

lookup_country_iso_codes
,根据工作目录中的
countries.json
,返回给定国家/地区名称的 2 位和 3 位 ISO 国家/地区代码。

`

def Lookup_country_iso_codes(country: str) -> 元组: ”“” >>> Lookup_country_iso_codes("台湾") ('TW','TWN') >>> Lookup_country_iso_codes("日本") (“日本”、“日本”) >>> Lookup_country_iso_codes("立陶宛") (“LT”、“LTU”) >>> Lookup_country_iso_codes("斯洛文尼亚") (“SI”、“SVN”) ”“”`

这是country.json的一部分:

[{   "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"}]

我不断收到 AssertionError: Tuples Difference: (None, None) != ('TW', 'TWN') ,我不知道问题是什么。 非常感谢!

python iso
1个回答
0
投票
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

# Example usage of the function
print(lookup_country_iso_codes("Taiwan"))  # ('TW', 'TWN')
print(lookup_country_iso_codes("Japan"))   # ('JP', 'JPN')

AssertionError 表明该函数未在您的countries.json 数据中找到指定的国家/地区。这可能是由于以下几个原因造成的。

  1. 国家/地区名称可能不匹配。确保 JSOn 文件中的名称与您要搜索的名称完全匹配。例如,如果您的 JSON 文件包含“中华民国(台湾)”而不是“台湾”,则该函数将找不到“台湾”的匹配项。
  2. 确保您的country.json 文件位于正确的目录中并且正在正确读取。
  3. 确保文件中的 JSON 结构与函数中的格式匹配。
  4. 如果您的 JSON 文件存在编码问题或特殊字符,可能会影响字符串匹配。

尝试上面修改后的功能。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.