我想構建一個簡單的應用程式,它將從城市詞典 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)
這在 VSCODE 中給出了一個很長的 JSON/Dictionary。如果可以訪問該隨機函式并從串列中隨機獲取一個單詞,我想我將能夠擴展這個想法。
任何幫助表示贊賞。
謝謝
uj5u.com熱心網友回復:
將《城市詞典》中的所有單詞都刮掉需要很長時間。您可以通過呼叫從 Urban Dictionary 中隨機獲取一個單詞https://api.urbandictionary.com/v0/random
這是一個從城市詞典中獲取隨機單詞的函式
def randomword():
response = requests.get("https://api.urbandictionary.com/v0/random")
return response.text
為了將回應轉換為 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
uj5u.com熱心網友回復:
參考上面的評論,我分享你需要的方法。
import requests
word = "all good in the hood"
response = requests.get(f"https://api.urbandictionary.com/v0/random")
# get all list item
for obj in response.json()['list']:
print(obj)
# get index 0 of list
print(response.json()['list'][0])
# get index 0 - word of list
print(response.json()['list'][0]['word'])
uj5u.com熱心網友回復:
文本為json格式,因此只需使用json模塊轉換為字典即可。我也有它只是給出了最多拇指的定義
import json
import requests
word = "all good in the hood"
response = requests.get(f"http://api.urbandictionary.com/v0/define?term={word}")
dictionary = json.loads(response.text)['list']
most_thumbs = -1
best_definition = ""
for definition in dictionary:
if definition['thumbs_up']>most_thumbs:
most_thumbs = definition['thumbs_up']
best_definition = definition['definition']
print(f"{word}: {best_definition}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372562.html
