heroku 如何在Python中使用requests模块获取特定类别的随机单词?

2eafrhcq  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(152)

我正在做一个Python项目,我需要从API(如Heroku)中获取一个随机单词,但只能是特定类别的单词,例如“Fruits”或“Colors”。我可以使用以下代码获取随机单词:

import requests
import random

try:
    url = "https://random-word-api.herokuapp.com/word?number=1"
    response = requests.get(url)
    words = response.json()
    random_word = random.choice(words)
    print(random_word)
except:
    print("Error fetching data from API")

字符串
我只是需要帮助实现“类别”功能现在。有人可以帮助吗?
我尝试使用以下代码块获取特定类别的随机单词:

import requests
import random

try:
    url = "https://random-word-api.herokuapp.com/word?number=1&category=fruits"
    response = requests.get(url)
    words = response.json()
    random_word = random.choice(words)
    print(random_word)
except:
    print("Error fetching data from API")


我本以为会得到一个随机的水果名称,比如“苹果”或“橙子”,但我得到了这样的信息:
“从API获取数据时出错”
(在except块中指定),这意味着发生了异常。

x33g5p2x

x33g5p2x1#

import requests

def fetch_random_word(category):
    base_url = 'https://wordsapiv1.p.rapidapi.com/words/'
    headers = {
        'X-RapidAPI-Host': 'wordsapiv1.p.rapidapi.com',
        'X-RapidAPI-Key': 'YOUR_RAPIDAPI_KEY',  # Replace with your actual RapidAPI key
    }

    # Make a request to the Words API
    response = requests.get(base_url, headers=headers, params={'random': 'true', 'category': category})

    # Check if the request was successful (status code 200)
    if response.status_code == 200:
        data = response.json()
        random_word = data['word']
        return random_word
    else:
        # If the request was not successful, print an error message
        print(f"Error: {response.status_code}")
        return None

# Example: Fetch a random word from the category 'food'
random_food_word = fetch_random_word('food')

if random_food_word:
    print(f"Random word in the 'food' category: {random_food_word}")
else:
    print("Failed to fetch a random word.")

字符串

相关问题