Skip to content

Instantly share code, notes, and snippets.

@LemonPrefect
Created December 6, 2022 05:27
Show Gist options
  • Save LemonPrefect/5e69068b67a5878c41314fa8211ddd7c to your computer and use it in GitHub Desktop.
Save LemonPrefect/5e69068b67a5878c41314fa8211ddd7c to your computer and use it in GitHub Desktop.
Deno script cli for query the syllables of word list from file.
import * as fs from "https://deno.land/std@0.167.0/node/fs.ts";
import axiod from "https://deno.land/x/axiod@0.26.2/mod.ts";
import { DOMParser } from "https://deno.land/x/deno_dom/deno-dom-wasm.ts";
import { colors } from "https://deno.land/x/cliffy@v0.25.5/ansi/colors.ts";
import { readLines } from "https://deno.land/std/io/buffer.ts";
const {error, warn, info} = {error: colors.bold.red, warn: colors.bold.yellow, info: colors.bold.blue};
export async function trans(word: string): Promise<string>{
word = word.split(" ")[0].trim();
const res = await axiod.get(`https://www.howmanysyllables.com/syllables/${word}`);
if(res.status !== 200){
console.log(error("[ERROR]"), `Web request to ${res.config.url} is FAILED. ${res.status}-${res.statusText}`);
return `[ERROR IN ${word}]`;
}
const document = new DOMParser().parseFromString(res.data, "text/html");
if(!document){
console.log(error("[ERROR]"), `Document parse FAILED.`);
return `[ERROR IN ${word}]`;
}
const container = document.querySelector("#SyllableContentContainer>.Answer_Red");
if(!container){
return "[NO SYLLABLE]";
}
return container!.textContent;
}
async function confirm(text: string){
console.log(text);
for await (const line of readLines(Deno.stdin)){
return;
}
}
if(!fs.existsSync("./in.txt")){
console.log(error("[ERROR]"), `./in.txt MISSING.`);
await confirm("Press ENTER to exit.");
}
const file: string = fs.readFileSync("./in.txt").toString().trim();
const words = file.split("\n");
let syllables: Array<string> = [];
const timestamp = new Date().getTime().toString();
let out = fs.openSync(`./out-${timestamp}.csv`, "a+");
for(let i = 0; i < words.length; i++){
words[i] = words[i].trim();
const syllable = await trans(words[i]);
syllables.push(syllable);
fs.writeFileSync(out, `${words[i]},${syllable}\n`);
console.log(info("[FOUND]"), `${i + 1}/${words.length}: ${words[i]}-${colors.green(syllable)}`);
}
fs.closeSync(out);
console.log(colors.green("[FINISHED]"));
await confirm("Press ENTER to exit.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment