This Gist was automatically created by Carbide, a free online programming environment.
Forked from carbide-public/Wiktionary API.carbide.md
Last active
February 5, 2022 00:10
-
-
Save jerbear2008/a5a1eebe56560899eb8d7f7c86d677c0 to your computer and use it in GitHub Desktop.
Wiktionary API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function define(e,n){let i=new RegExp('< *\\/? *[a-z]+ *( [a-z]+="[^<>"]+" *)* *\\/? *>',"ig");function t(e){return e.replaceAll(i,"").replaceAll(" "," ")}let f="https://en.wiktionary.org/api/rest_v1/page/definition/"+e,a=await fetch(f),o=await a.json(),r="";for(let e of o[n]){r+=e.partOfSpeech;for(let n of e.definitions)if(n.definition){if(r+="\n- "+t(n.definition),n.examples)for(let e of n.examples){r+=`\n "${t(e)}"`}}r+="\n\n"}return r.trim()} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let word = 'define' ///++Word input++ | |
let lang = 'en' | |
let endpoint = 'https://en.wiktionary.org/api/rest_v1/page/definition' ///Wiktionary endpoint\\Docs: ++https://en.wiktionary.org/api/rest\_v1/#/Page%20content/get\_page\_definition\_\_term\_++ | |
let filter = new RegExp('< *\\/? *[a-z]+ *( [a-z]+="[^<>"]+" *)* *\\/? *>', 'ig') ///Filter to clean out html | |
function cleanString(str) { ///Function to clean string with filter and remove | |
return str.replaceAll(filter, '').replaceAll(' ', ' ') | |
} | |
let url = `${endpoint}/${word}` ///Url to fetch | |
let resObj = await fetch(url) ///Fetch url | |
let res = await resObj.json() ///Convert to JSON | |
let output = '' | |
for (let meaning of res[lang]) { ///Repeat over meanings | |
output += meaning.partOfSpeech ///Add part of speech | |
for (let definition of meaning.definitions) { ///Repeat over definitions | |
if (definition.definition) { | |
let filteredDefinition = cleanString(definition.definition) ///Clean and add definition string | |
output += `\n- ${filteredDefinition}` | |
if (definition.examples) { | |
for (let example of definition.examples) { ///Repeat over examples | |
let filteredExample = cleanString(example) ///Filter and add example | |
output += `\n "${filteredExample}"` | |
} | |
} | |
} | |
} | |
output += '\n\n' ///Add newlines | |
} | |
output = output.trim() ///Trim output | |
console.log(output) | |
output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment