You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取JSON货币接口数据匹配国家前缀时始终无匹配的bug求助

问题修复:货币匹配程序始终无结果的BUG

问题根源

  1. 语法错误:代码首行mport requests漏写字母i,应为import requests,这会直接导致库导入失败。
  2. 数据结构误判:遍历data['symbols']时,每个元素的值是字典而非字符串。原代码里description变量实际对应{'code': 'XXX', 'description': 'XXX'}这样的结构,isinstance(description, str)永远为False,完全跳过了匹配逻辑。
  3. 大小写不兼容:用户输入的字母大小写可能和接口返回的描述不一致,直接匹配会漏掉符合条件的结果。

修复后的完整代码

import requests

url = 'https://api.exchangerate.host/symbols'
response = requests.get(url)
data = response.json()

def find_matching_currencies(input_letters):
    matching_currencies = []
    # 统一转小写,避免大小写匹配遗漏
    input_lower = input_letters.lower()
    for code, currency_info in data['symbols'].items():
        # 取出字典中的描述字段,转小写后匹配
        desc_lower = currency_info['description'].lower()
        if input_lower in desc_lower:
            matching_currencies.append((currency_info['description'], code))
    return matching_currencies

def main():
    user_input = input("Please Enter the FIRST THREE Letters of Your Country: ")
    matching_currencies = find_matching_currencies(user_input)
    if matching_currencies:
        print("Following is the result based on your input:")
        for description, code in matching_currencies:
            print(f'Your Currency name is: {description} and the code for it is: {code}')
    else:
        print("There is NO match against the input you provided.")

if __name__ == "__main__":
    main()

核心修复说明

  • 修正了import的拼写错误,确保requests库能正常导入。
  • 调整遍历逻辑:将循环变量改为currency_info,通过currency_info['description']获取真实的描述文本,修正了原代码对数据结构的错误理解。
  • 增加大小写统一转换:把用户输入和描述文本都转成小写后再匹配,解决了大小写不一致导致的匹配失败问题。
  • 移除了多余的isinstance判断,因为接口返回的symbols结构是固定的,每个项都是包含description字段的字典。

内容的提问来源于stack exchange,提问作者webquest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:05:30