Pre*_*vis 1 python api json web-scraping python-requests
我想构建一个简单的应用程序,它将从城市词典 API 生成随机单词及其相关定义。我想我可以以某种方式抓取网站或找到包含大多数城市词典单词的数据库或 .csv 文件,然后将其注入 api {word} 中。
我在这里找到了他们的非官方/官方 API: http: //api.urbandictionary.com/v0
有关于此的更多信息: https: //pub.dev/documentation/urbandictionary/latest/urbandictionary/OfficialUrbanDictionaryClient-class.html 这里: https: //pub.dev/documentation/urbandictionary/latest/urbandictionary/UrbanDictionary-class .html
在第二个 pub.dev 链接中似乎有一个内置函数,可以从网站生成随机单词列表。显然,这将是创建此应用程序的更好方法,而不是必须找到数据库/网络抓取单词。问题是我不知道如何在我的代码中调用该函数。
API 新手,到目前为止我的代码:
import requests
word = "all good in the hood"
response = requests.get(f"http://api.urbandictionary.com/v0/define?term={word}")
print(response.text)
Run Code Online (Sandbox Code Playgroud)
这在 VSCODE 中给出了一个很长的 JSON/字典。我想如果可以访问该随机函数并从列表中获取一个随机单词,我就能够扩展这个想法。
任何帮助表示赞赏。
谢谢
抓取城市词典中的所有单词需要很长时间。您可以通过调用从城市词典中获取随机单词https://api.urbandictionary.com/v0/random
这是一个从 Urban Dictionary 中获取随机单词的函数
def randomword():
response = requests.get("https://api.urbandictionary.com/v0/random")
return response.text
Run Code Online (Sandbox Code Playgroud)
为了将响应转换为 JSON,您必须导入 JSON 并执行json.loads(response.text). 一旦转换为 JSON,它基本上就是一个字典。这是获取第一个定义的定义、单词和作者的代码
data = json.loads(randomword()) #gets random and converts to JSON
firstdef = data["list"][0] #gets first definition
author = firstdef["author"] #author of definition
definition = firstdef["definition"] #definition of word
word = firstdef["word"] #word
Run Code Online (Sandbox Code Playgroud)