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

2eafrhcq  于 2024-01-08  发布在  Python
关注(0)|答案(1)|浏览(206)

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

  1. import requests
  2. import random
  3. try:
  4. url = "https://random-word-api.herokuapp.com/word?number=1"
  5. response = requests.get(url)
  6. words = response.json()
  7. random_word = random.choice(words)
  8. print(random_word)
  9. except:
  10. print("Error fetching data from API")

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

  1. import requests
  2. import random
  3. try:
  4. url = "https://random-word-api.herokuapp.com/word?number=1&category=fruits"
  5. response = requests.get(url)
  6. words = response.json()
  7. random_word = random.choice(words)
  8. print(random_word)
  9. except:
  10. print("Error fetching data from API")


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

x33g5p2x

x33g5p2x1#

  1. import requests
  2. def fetch_random_word(category):
  3. base_url = 'https://wordsapiv1.p.rapidapi.com/words/'
  4. headers = {
  5. 'X-RapidAPI-Host': 'wordsapiv1.p.rapidapi.com',
  6. 'X-RapidAPI-Key': 'YOUR_RAPIDAPI_KEY', # Replace with your actual RapidAPI key
  7. }
  8. # Make a request to the Words API
  9. response = requests.get(base_url, headers=headers, params={'random': 'true', 'category': category})
  10. # Check if the request was successful (status code 200)
  11. if response.status_code == 200:
  12. data = response.json()
  13. random_word = data['word']
  14. return random_word
  15. else:
  16. # If the request was not successful, print an error message
  17. print(f"Error: {response.status_code}")
  18. return None
  19. # Example: Fetch a random word from the category 'food'
  20. random_food_word = fetch_random_word('food')
  21. if random_food_word:
  22. print(f"Random word in the 'food' category: {random_food_word}")
  23. else:
  24. print("Failed to fetch a random word.")

字符串

展开查看全部

相关问题