在 JSON 文件中搜索数据并使用 Python 显示它

Searching data in the JSON File and displaying it using Python

提问人:webquest 提问时间:8/19/2023 更新时间:8/20/2023 访问量:55

问:

我在“https://api.exchangerate.host/symbols”处有一个 JSON,表单中有数据

'symbols': {'AED': {'code': 'AED', 'description': '阿拉伯联合酋长国迪拉姆'}, 'AFN': {'code': 'AFN', 'description': '阿富汗尼'}, ..........

在下面的程序中,我无法修复错误以获得所需的输出,而是始终提供相同的输出(对于任何三个字母,作为输入),即“与您提供的输入没有匹配”。

mport requests
#from pprint import PrettyPrinter

#printer = PrettyPrinter()

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

def find_matching_currencies(input_letters):
    matching_currencies = []
    for code, description in data['symbols'].items():
        if isinstance(description, str) and input_letters in description:
            matching_currencies.append((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()

我曾经以多种方式编写程序,但无法获得所需的结果,即如果用户输入他所在国家/地区的前三个“字母表”,那么他应该从 JSON 文件中获取货币的“代码”以及以下格式的“描述”: print(f'你的货币名称是:{description},它的代码是:{code}')

Python JSON 字典 搜索 使用

评论


答:

0赞 John Gordon 8/19/2023 #1
for code, description in data['symbols'].items():
    if isinstance(description, str) and input_letters in description:

这个 if 语句永远不会是真的,因为是一个子字典;它不是一个普通的字符串。description

"symbols": {
    "AED":{"description":"United Arab Emirates Dirham","code":"AED"},
    "AFN":{"description":"Afghan Afghani","code":"AFN"},
    "ALL":{"description":"Albanian Lek","code":"ALL"},
    "AMD":{"description":"Armenian Dram","code":"AMD"},
    "ANG":{"description":"Netherlands Antillean Guilder","code":"ANG"},
    ...
 }
0赞 Codist 8/19/2023 #2

您的搜索条件没有多大意义。JSON 响应中的“description”值是货币的正确名称。获取国家/地区名称的前 3 个字母并在描述中搜索将显示模棱两可的结果。例如。。。如果用户输入是 FRA 怎么办?这些是法国的前三个字母,但结果与该国无关。

下面是代码的简化,希望能更清楚地说明如何解决这个问题:

import requests

URL = 'https://api.exchangerate.host/symbols'

def find_matching_currencies(currency):
    values = []
    with requests.get(URL) as response:
        response.raise_for_status()
        j = response.json()
        if j['success']:
            for k, v in j['symbols'].items():
                if currency in (d := v['description']).lower():
                    values.append((d, k))
    return values

currency = input('Enter part of a currency name: ').lower()

print(*find_matching_currencies(currency), sep='\n')

安慰:

Enter part of a country name: fra
('Burundian Franc', 'BIF')
('Congolese Franc', 'CDF')
('Swiss Franc', 'CHF')
('Djiboutian Franc', 'DJF')
('Guinean Franc', 'GNF')
('Comorian Franc', 'KMF')
('Rwandan Franc', 'RWF')
('CFA Franc BEAC', 'XAF')
('CFA Franc BCEAO', 'XOF')
('CFP Franc', 'XPF')
0赞 Mohamad Raad 8/20/2023 #3

这可能有效:

import requests

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

def find_matching_currencies(input_letters):
    matching_currencies = []
    for code, description in data['symbols'].items():
        if input_letters.upper() in code:
            matching_currencies.append((description, code))
    return matching_currencies

def main():
    user_input = input("Please Enter the FIRST THREE Letters of Your Currency: ")
    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["description"]} and the code for it is: {code}')
    else:
        print("There is NO match against the input you provided.")

if __name__ == "__main__":
    main()