【问题标题】:How to filter an API Search result in Python?如何在 Python 中过滤 API 搜索结果?
【发布时间】:2021-06-08 17:33:18
【问题描述】:

我正在使用edamam recipe api,并且一直在尝试通过仅保存卡路里数 > 用户输入的最大值的食谱来过滤响应。我不断收到错误消息。这是代码:

import requests
import pandas as pd


def recipe_search(ingredient):
    app_id = ''
    app_key = ''
    result = requests.get('https://api.edamam.com/search?q={}&app_id={}&app_key={}'.format(ingredient, app_id, app_key))
    data = result.json()
    return data['hits']


def run():
    ingredient = input('Enter an ingredient: ')
    max_no_of_calories = float(input('Enter the max amount of calories desired in recipe: '))
    data_label = []
    data_uri = []
    data_calories = []
    results = recipe_search(ingredient)

    for result in results:
        recipe = result['recipe']
        result['calories'] < max_no_of_calories
        data_label.append(recipe['label'])
        data_uri.append(recipe['uri'])
        data_calories.append(recipe['calories'])
        data = {'Label': data_label,
                'URL': data_uri,
                'No of Calories': data_calories
                }
        df = pd.DataFrame(data, columns=['Label', 'URL'])
        df.to_csv(r'C:\Users\name\Documents/cfg-python/export_dataframe.csv',
                  index=False, header=True)


run()
df2 = pd.read_csv(r'C:\Users\name\Documents/cfg-python/export_dataframe.csv')
sorted_df = df2.sort_values(by=["calories"], ascending=True)
sorted_df.to_csv(r'C:\Users\name\Documents/cfg-python/export_dataframe.csv', index=False)

这是错误:

if result['calories'] < max_no_of_calories:
KeyError: 'calories'

有人可以帮忙吗?如何使用max_no_of_calories 下的仅食谱过滤器重新编写此代码? 'max_no_of_calories' 由用户输入。

【问题讨论】:

  • docs 表示您可以在 GET 请求中传递 calories= 参数。 “格式为卡路里=范围,其中范围由千卡中的值替换。范围是 MIN+、MIN-MAX 或 MAX 之一,其中 MIN 和 MAX 是非负整数。+ 符号需要正确编码。示例:“calories=100-300”将返回每份热量在 100 到 300 kcal 之间的所有食谱。”
  • 你好波莉,欢迎来到 SO。我想你应该隐藏你的 API 密钥,除非它是公开的。

标签: python pandas python-requests edamam-api


【解决方案1】:

你在 for 循环中打错了

for result in results:
    recipe = result['recipe']
    if recipe["calories"] < max_no_of_calories:
        print(recipe["calories"])

这将消除您的关键错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-07
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2012-05-18
    • 2010-11-15
    相关资源
    最近更新 更多