0

嘿,伙计们,这将是一个艰巨的任务,但我需要帮助改进这段代码,它仍然不能完全按照我的意愿去做。我是一名研究生,试图利用Edamam Nutrition Analysis API从该数据集中获取食物的卡路里信息。

我需要帮助改进此代码,因为它连接到 API 并获取食物信息,但这是我的担忧:

  1. 它不会keys像我想要的那样每 10 个查询调用循环遍历列表中的 api 键。字典中的键值headers应该更改为keys列表中的下一个 API 键,如下示例输出所示:
Detected Word:  waffle
Food Stats: 
 {"message":"You have exceeded the DAILY quota for requests on your current plan, BASIC. Upgrade your plan at https:\/\/rapidapi.com\/edamam\/api\/edamam-nutrition-analysis"}
Out of calls, restarting in 30 secs...
x at 1
Key 1 : 16d7ecf46dmshc432a0e5b44478bp18c531jsn775dccbe9451
Detected Word:  butter
Food Stats: 
 {"message":"You have exceeded the DAILY quota for requests on your current plan, BASIC. Upgrade your plan at https:\/\/rapidapi.com\/edamam\/api\/edamam-nutrition-analysis"}
Out of calls, restarting in 30 secs...
x at 2 
Key 2 : 16d7ecf46dmshc432a0e5b44478bp18c531jsn775dccbe9451    # Supposed to
# switch to next key in keys list upon this error message happening
Detected Word:  syrup
Food Stats: 
 {"message":"You have exceeded the DAILY quota for requests on your current plan, BASIC. Upgrade your plan at https:\/\/rapidapi.com\/edamam\/api\/edamam-nutrition-analysis"}
Out of calls, restarting in 30 secs...
x at 3 # AFTER 2 IT IS SUPPOSED TO RESET TO 0!!
Key 3 : 16d7ecf46dmshc432a0e5b44478bp18c531jsn775dccbe9451
Detected Word:  ham
Food Stats: 
 {"message":"You have exceeded the DAILY quota for requests on your current plan, BASIC. Upgrade your plan at https:\/\/rapidapi.com\/edamam\/api\/edamam-nutrition-analysis"}
Out of calls, restarting in 30 secs...
x at 4 

  1. 我认为我使用了太多的ifandelse语句,我最近这样做是因为我有一些if语句没有else,并且认为添加else将确保所有代码都被执行。

  2. 我的编程逻辑合理吗?

  3. 有没有人知道一个可以做 Edamam Nutrition API 的功能但免费的食物 API ?我只是想让这个工作,但要完成我想要的,我必须拨打比系统允许的更多的电话。

  4. 我在最后添加列表的方式是否会产生到我寻求的输出列/系列?我想要的输出如下所示:

# each list will be the length of the # of food items detected in the respective text data, the numbers
# being the calories of that food item.
[[23,23,22], [23,543,76, 322, 32, 1], [31,312,67,34,34,2], [31,543,76,32,12], [32,4,66,3], etc...]

这是代码:

col = []
sem = []
while len(col) != len(data['post']):
    for i in data['post']:

        limit = 0
        calories = []
        for word in eval(i):
            if word not in food:
                continue
            else:
                print('Detected Word: ', word)
                querystring = {"ingr": "1 {}".format(word)}

                try: # ERROR HANDLING: CHECK FOR KEY ERROR
                    response = requests.request("GET", url, headers=headers, params=querystring)
                except KeyError as f:
                    print(f, 'Out of calls, restarting in 30 secs...')
                    time.sleep(30)
                    x += 1                      # move on to next API key as result of error
                    if ctrl == (len(keys) - 1):
                        x -= 2                  # move back to keys[0]: first API key
                        print(x)
                        print('Key', x, ':', key)
                else:
                    stats = response.text
                    print('Food Stats: \n', stats)

                    if 'status' or 'message' in eval(stats).keys(): # ERROR HANDLING: CHECKS FOR THESE KEY VALUES
                                                                    # TO DETECT RUNNING OUT OF API CALLS
                        print('Out of calls, restarting in 30 secs...')
                        time.sleep(30)
                        x += 1                               # move on to next API key as result of error
                        if ctrl == (len(keys) - 1):
                            x -= 2                           # move back to keys[0]: first API key
                        else:
                            print(x)
                            print('Key', x, ':', key)

                    else:
                        calories.append(eval(stats)['calories'])
                        limit += 1
                        print('Limit at {}'.format(limit))
                        if limit == 10:
                            x += 1
                            print(x)
                            if ctrl == (len(keys) - 1):
                                x -= 2
                                print('Reset x:', x)
                                print('Key', x, ':', key)
                        else:
                            print('Limit at {}, Halting program for 30 secs...'.format(limit))
                            limit = 0
                            time.sleep(30)
                            print('Resuming...')
                    sem.append(calories)
                col.append(sem)

以下是此代码涉及的变量:

# dataset where we are getting text data from

data = pd.read_csv('mfp_1_proc_data.csv')


# Manual Food Bank to check if words are food.

food = ['waffle', 'apple', 'cottage', 'cheese', 'muffin', 'soup', 'coffee', 'butter', 'ham', 'syrup', 'tortilla',
        'salt', 'pepper', 'butternut', 'walnut', 'cinnamon', 'kale', 'spinach', 'banana', 'bean', 'turkey', 'jam',
        'carrot', 'cracker', 'rice', 'soy', 'tempura', 'sushi', 'orange', 'pasta', 'chicken', 'beef', 'fish', 'lamb',
        'pork', 'broccoli', 'lettuce', 'tomato', 'garlic', 'bacon', 'salad', 'vanilla', 'raspberry', 'cake', 'beer',
        'green', 'onion', 'vegetable', 'chocolate', 'sugar', 'chip', 'cookie', 'milk', 'cashew', 'vinegar', 'artichoke',
        'cheddar', 'cauliflower', 'pinto', 'egg', 'peanut', 'cocoa', 'avocado', 'pomegranate', 'clementine', 'grape']

# API keys to be cycled through operation

keys = ["16d7ecf46dmshc432a0e5b44478bp18c531jsn775dccbe9451",
        "e5d3101980msh4437c99f8467336p1f07a7jsne6206fb9828d",
        "f3d0adb9bamsh765dd46a0f7169ep1bbb31jsn68420afd160b"]

# variable for keys[x] to change which key is used

x = 0

# Dictionary to run as headers parameter for requests.request()
# 'x-rapidapi-key' value is meant to be changed to the next key in the keys list every 10 queries

headers = {
                'x-rapidapi-host': "edamam-edamam-nutrition-analysis.p.rapidapi.com",
                'x-rapidapi-key': keys[x]
            }

# useful variable to refer to headers key

key = headers['x-rapidapi-key']

# this should equal the index of whatever API key from the keys list key equals (if headers['x-rapidapi-key'] = keys[2],
# ctrl = 2)

ctrl = keys.index(key)

如果这不是提出此类问题的正确论坛,请告诉我。如果你们能提供帮助,我们将不胜感激,因为这些数据将帮助我的研究项目走上一条清晰的完成之路。

4

0 回答 0