diff --git a/Readme.md b/Readme.md index df99879..dcbdac7 100644 --- a/Readme.md +++ b/Readme.md @@ -34,6 +34,7 @@ Small tools Halit Sever uses himself, at tools.halit.org. They run in your brows - [**Slug generator**](https://tools.halit.org/slug-generator/) - turns titles into URL slugs: lowercase, a hyphen, underscore or dot between words, accented and Turkish letters (ç, ğ, ı, İ, ö, ş, ü) made plain or kept, German umlauts as ae, oe and ue on request, optional English stop word removal and a maximum length that keeps whole words. One slug per line for a list of titles. English only. - [**Remove special characters**](https://tools.halit.org/remove-special-characters/) - removes punctuation, symbols, emoji and invisible characters from text and turns accented letters into plain ones (é to e, ß to ss, Turkish ı and İ to i and I), with a keep list for characters such as @ or the hyphen, an option to put a space where a character was, collapsed spaces, lowercase and an a to z only mode. Turkish version: [Türkçe karakter temizleme](https://tools.halit.org/tr/turkce-karakter-temizleme/), which also repairs garbled Turkish such as ü and ı (UTF-8 read as Windows-1252 or 1254). - [**Kelime ve karakter sayacı**](https://tools.halit.org/tr/karakter-sayaci/) - word and character counter: words, characters with and without spaces, letters, sentences and paragraphs as you type, a reading time at a speed you set, a character limit and a count for the selected part. Words follow Unicode word boundaries (UAX #29), so apostrophes such as İstanbul'da keep a word whole; characters are grapheme clusters, so an emoji counts once. Turkish only. +- [**Word frequency counter**](https://tools.halit.org/word-frequency-counter/) - ranks every word in a text by how often it appears, with its count and its share of all words (keyword density). Counts two- and three-word phrases inside one sentence, leaves out English stop words on request, has a Turkish casing option for I and İ, and copies the table for a spreadsheet or downloads it as CSV. English only. - **Stays on your device** - every tool is plain JavaScript in the page. A Content Security Policy blocks connections to any server except the Cloudflare Web Analytics page-view beacon, so pasted text cannot be sent anywhere. - **English and Turkish** - each page has a Turkish twin written in Turkish, paired with `hreflang`. diff --git a/public/og/word-frequency-counter.png b/public/og/word-frequency-counter.png new file mode 100644 index 0000000..96e2cbd Binary files /dev/null and b/public/og/word-frequency-counter.png differ diff --git a/public/site.css b/public/site.css index d298872..3542540 100644 --- a/public/site.css +++ b/public/site.css @@ -1781,6 +1781,72 @@ code { display: none; } +/* word frequency counter: the table scrolls inside the output pane */ +.pane-title { + font-size: 14px; + font-weight: 600; +} + +/* a fixed height, or a long list would stretch both panes */ +.freq-wrap { + flex: none; + height: 440px; + min-height: 0; + overflow: auto; + background: color-mix(in srgb, var(--muted) 45%, var(--card)); +} + +.freq-wrap:focus-visible { + outline: 2px solid var(--ring); + outline-offset: -2px; +} + +.freq-empty { + padding: 16px 20px; + color: var(--muted-foreground); + font-size: 15px; +} + +.freq-empty[hidden], +.freq[hidden] { + display: none; +} + +.freq th { + position: sticky; + top: 0; + background: var(--card); +} + +.freq th:first-child, +.freq td:first-child { + width: 4.5em; + padding-left: 20px; + color: var(--muted-foreground); +} + +.freq .word { + overflow-wrap: anywhere; +} + +.freq td:last-child, +.freq th:last-child { + padding-right: 20px; +} + +.stopwords { + max-width: 72ch; + margin-top: 16px; + color: var(--muted-foreground); + font: 400 13px/1.7 var(--font-mono); +} + +@media (max-width: 833px) { + .freq-wrap { + height: 360px; + } +} + /* word and character counter: the text gets the wider column */ .counter { grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr); diff --git a/scripts/browser-check.mjs b/scripts/browser-check.mjs index 50575b1..c7417fd 100644 --- a/scripts/browser-check.mjs +++ b/scripts/browser-check.mjs @@ -921,12 +921,64 @@ for (const width of [1280, 390]) { await context.close(); } +const FREQUENCY = "/word-frequency-counter/"; +for (const width of [1280, 390]) { + const label = `en frequency ${width}`; + const { context, page, errors } = await open(width, FREQUENCY, label); + await page.evaluate(() => localStorage.clear()); + await page.reload({ waitUntil: "networkidle" }); + const rows = () => page.$$eval("#rows tr", (trs) => trs.map((tr) => [...tr.children].map((td) => td.textContent))); + expect(await page.isVisible("#empty"), `${label}: empty note hidden`); + await page.fill("#src", "The cat and the hat. The cat sat. Don't stop, don’t!"); + let r = await rows(); + expect(JSON.stringify(r.slice(0, 3)) === JSON.stringify([["1", "the", "3", "27.27"], ["2", "cat", "2", "18.18"], ["3", "don't", "2", "18.18"]]), `${label}: words ${JSON.stringify(r.slice(0, 3))}`); + expect((await page.textContent("#counts")) === "11 words · 7 unique", `${label}: counts ${await page.textContent("#counts")}`); + await page.check('input[data-option="stopwords"]'); + r = await rows(); + expect(r.map((x) => x[1]).join(",") === "cat,hat,sat,stop", `${label}: stop words ${JSON.stringify(r)}`); + await page.locator('input[name="size"][value="2"]').check({ force: true }); + await page.fill("#src", "Word frequency counter. A word frequency counter counts words."); + r = await rows(); + expect(r[0][1] === "frequency counter" && r[0][2] === "2" && r[1][1] === "word frequency" && (await page.textContent("#col-word")) === "Phrase", `${label}: phrases ${JSON.stringify(r)}`); + await page.reload({ waitUntil: "networkidle" }); + expect((await page.isChecked('input[name="size"][value="2"]')) && (await page.isChecked('input[data-option="stopwords"]')), `${label}: options not remembered`); + await page.click("#reset"); + expect((await page.isChecked('input[name="size"][value="1"]')) && !(await page.isChecked('input[data-option="stopwords"]')), `${label}: reset`); + await page.fill("#src", "IŞIK ışık İzmir izmir 2026 a"); + expect((await rows()).map((x) => x[1]).join(",") === "izmir,2026,a,işik,ışık", `${label}: english casing ${JSON.stringify(await rows())}`); + await page.check('input[data-option="turkish"]'); + await page.uncheck('input[data-option="numbers"]'); + await page.fill("#min", "2"); + expect((await rows()).map((x) => x[1]).join(",") === "ışık,izmir", `${label}: turkish ${JSON.stringify(await rows())}`); + await page.click("#reset"); + await page.fill("#src", "Alpha beta beta"); + await page.click("#copy"); + await page.waitForTimeout(150); + const copied = await page.evaluate(() => navigator.clipboard.readText()); + expect(copied === "Rank\tWord\tCount\tPercent\n1\tbeta\t2\t66.67\n2\talpha\t1\t33.33", `${label}: copy ${JSON.stringify(copied)}`); + const [download] = await Promise.all([page.waitForEvent("download"), page.click("#csv")]); + const file = await download.path(); + const { readFile: rf } = await import("node:fs/promises"); + const csv = (await rf(file, "utf8")).replace(/^\uFEFF/, ""); + expect(download.suggestedFilename() === "word-frequency.csv" && csv === "Rank,Word,Count,Percent\r\n1,beta,2,66.67\r\n2,alpha,1,33.33", `${label}: csv ${JSON.stringify(csv)}`); + const words = Array.from({ length: 700 }, (_, i) => `w${i}`).join(" "); + await page.fill("#src", words); + expect((await page.locator("#rows tr").count()) === 500 && (await page.textContent("#counts")).includes("showing the top 500"), `${label}: row cap`); + await page.fill("#src", ""); + expect(await page.isVisible("#empty"), `${label}: empty after clear`); + await page.fill("#src", "A word frequency counter shows how often each word appears in a text. Paste a text, and the counter ranks every word, so the words you repeat most stand out. The counter also counts phrases."); + await page.screenshot({ path: `${shots}/en-frequency-${width}.png`, fullPage: true }); + await langMenu(page, label, "en", { en: FREQUENCY, tr: "/tr/" }, null); + finish(errors, label); + await context.close(); +} + for (const path of OTHER) { for (const width of [1440, 390]) { const label = `${path} ${width}`; const { context, page, errors } = await open(width, path, label); await page.screenshot({ path: `${shots}/page${path.replace(/\//g, "_")}-${width}.png`, fullPage: true }); - if (path !== "/missing-page") expect((await page.locator(".tool-card").count()) === 16, `${label}: index does not list every tool`); + if (path !== "/missing-page") expect((await page.locator(".tool-card").count()) === 17, `${label}: index does not list every tool`); if (path !== "/missing-page") expect((await page.locator('.tool-card a[href="/tr/kdv-hesaplama/"]').count()) === 1, `${label}: index does not link KDV`); if (path !== "/missing-page") expect((await page.locator('.tool-card a[href="/tr/yas-hesaplama/"]').count()) === 1, `${label}: index does not link yaş hesaplama`); if (path !== "/missing-page") expect((await page.locator('.tool-card a[href="/days-between-dates/"]').count()) === 1, `${label}: index does not link days between dates`); @@ -939,6 +991,7 @@ for (const path of OTHER) { if (path !== "/missing-page") expect((await page.locator('.tool-card a[href="/slug-generator/"]').count()) === 1, `${label}: index does not link the slug generator`); if (path !== "/missing-page") expect((await page.locator(`.tool-card a[href="${SPECIAL[path === "/tr/" ? "tr" : "en"]}"]`).count()) === 1, `${label}: index does not link the special character remover`); if (path !== "/missing-page") expect((await page.locator('.tool-card a[href="/tr/karakter-sayaci/"]').count()) === 1, `${label}: index does not link the counter`); + if (path !== "/missing-page") expect((await page.locator('.tool-card a[href="/word-frequency-counter/"]').count()) === 1, `${label}: index does not link the word frequency counter`); const lang = path === "/tr/" ? "tr" : "en"; await langMenu(page, label, lang, HOME, `${shots}/menu${path.replace(/\//g, "_")}-${width}.png`); finish(errors, label); diff --git a/scripts/build.mjs b/scripts/build.mjs index e1c9e79..ac93729 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -523,6 +523,35 @@ ${row("reading", u.reading)} `; } +/** Phrase length and minimum length above the panes, the ranked table where the output text would be. */ +function frequencyTool(page) { + const u = page.ui; + return `
+
+
${esc(u.size)}
${u.sizes.map(([v, l], i) => radio("size", v, l, i === 0)).join("")}
+
${esc(u.minHint)}
+
+
+
+
+ +
+
+
${esc(u.output)}
+
+

${esc(u.empty)}

+ +
+
+
+
${esc(u.zero)}
+
+
${esc(u.options)}
+
${page.options.map(checkbox).join("")}
+
+
`; +} + const SWAP = ``; const OPEN = ``; const MINUS = ``; @@ -670,7 +699,7 @@ ${row("weekend", u.weekend)} `; } -const TOOL_BODY = { paste: pasteTool, linebreaks: lineBreaksTool, case: caseTool, color: colorTool, invisible: invisibleTool, repeater: repeaterTool, chmod: chmodTool, slug: slugTool, special: specialTool, counter: counterTool, reverse: caseTool, flip: pasteTool, compare: compareTool, kdv: kdvTool, yas: yasTool, dates: datesTool }; +const TOOL_BODY = { paste: pasteTool, linebreaks: lineBreaksTool, case: caseTool, color: colorTool, invisible: invisibleTool, repeater: repeaterTool, chmod: chmodTool, slug: slugTool, special: specialTool, counter: counterTool, frequency: frequencyTool, reverse: caseTool, flip: pasteTool, compare: compareTool, kdv: kdvTool, yas: yasTool, dates: datesTool }; /** Prose, a list of titled rows with sources, and a dated note; the paste and compare pages build theirs from why and shortcuts. */ function infoSection(page, sec) { @@ -826,7 +855,7 @@ await mkdir(OUT, { recursive: true }); await cp(new URL("../public/", import.meta.url), OUT, { recursive: true }); await rm(new URL("signature.svg", OUT)); await writeFile(new URL("site.css", OUT), minifyCss((await read("../tokens.css")) + "\n" + (await read("../public/site.css")))); -for (const f of ["clean.js", "plain-text.js", "diff.js", "text-compare.js", "kdv.js", "kdv-hesaplama.js", "yas.js", "yas-hesaplama.js", "date-diff.js", "days-between-dates.js", "line-breaks.js", "remove-line-breaks.js", "case.js", "case-converter.js", "color.js", "hex-to-rgb.js", "invisible.js", "invisible-character.js", "repeat.js", "text-repeater.js", "reverse.js", "reverse-text.js", "flip.js", "upside-down-text.js", "chmod.js", "chmod-calculator.js", "slug.js", "slug-generator.js", "special.js", "remove-special-characters.js", "count.js", "karakter-sayaci.js", "nav.js"]) await cp(new URL(`../src/${f}`, import.meta.url), new URL(f, OUT)); +for (const f of ["clean.js", "plain-text.js", "diff.js", "text-compare.js", "kdv.js", "kdv-hesaplama.js", "yas.js", "yas-hesaplama.js", "date-diff.js", "days-between-dates.js", "line-breaks.js", "remove-line-breaks.js", "case.js", "case-converter.js", "color.js", "hex-to-rgb.js", "invisible.js", "invisible-character.js", "repeat.js", "text-repeater.js", "reverse.js", "reverse-text.js", "flip.js", "upside-down-text.js", "chmod.js", "chmod-calculator.js", "slug.js", "slug-generator.js", "special.js", "remove-special-characters.js", "count.js", "karakter-sayaci.js", "frequency.js", "word-frequency-counter.js", "nav.js"]) await cp(new URL(`../src/${f}`, import.meta.url), new URL(f, OUT)); const built = []; for (const page of pages.list) { diff --git a/scripts/content.mjs b/scripts/content.mjs index 6695c16..784fbc8 100644 --- a/scripts/content.mjs +++ b/scripts/content.mjs @@ -1,6 +1,7 @@ /** Page copy for both languages. The Turkish pages are written in Turkish, not translated line by line. */ import { flipText, FLIP_TABLE } from "../src/flip.js"; import { toSymbolic } from "../src/chmod.js"; +import { STOPWORDS } from "../src/frequency.js"; const k = (...keys) => keys.map((key) => `${key}`).join("+"); const a = (href, text) => `${text}`; @@ -605,6 +606,39 @@ export const TOOLS = [ demoToText: "4 kelime · 25 karakter", }, }, + { + id: "word-frequency-counter", + en: { + path: "/word-frequency-counter/", + name: "Word frequency counter", + blurb: "Ranks every word in a text by how often it appears, with counts and percentages, two- and three-word phrases, stop word filtering and CSV export.", + about: [ + "Paste text and see every word ranked by how often it appears, with its count and its share of all words.", + "Counts two- and three-word phrases too, skips stop words on request and exports the table as CSV.", + ], + demo: "pair", + demoBefore: "Text", + demoAfter: "Most frequent", + demoFromText: "the cat and the hat", + demoToText: "the 2 · and 1 · cat 1", + }, + tr: { + path: "/word-frequency-counter/", + lang: "en", + name: "Kelime sıklığı sayacı (İngilizce)", + blurb: "Metindeki her kelimeyi kaç kez geçtiğine göre sıralar; sayı ve yüzdeyle, iki ve üç kelimelik ifadelerle, CSV olarak indirme seçeneğiyle. Sayfa İngilizce.", + about: [ + "Metni yapıştır, her kelimenin kaç kez geçtiğini ve tüm kelimeler içindeki payını gör.", + "İki ve üç kelimelik ifadeleri de sayar, tabloyu CSV olarak verir. Türkçe büyük-küçük harf seçeneği var; sayfa yalnızca İngilizce.", + ], + demo: "pair", + demoBefore: "Metin", + demoAfter: "En sık", + demoFromText: "bir elma bir armut", + demoToText: "bir 2 · armut 1 · elma 1", + badge: "İngilizce", + }, + }, ]; const tool = TOOLS[0]; @@ -3788,8 +3822,161 @@ const trCounter = { }; trCounter.jsonLd = [toolPage("tr", trCounter, counters), faqLd(trCounter.faq)]; +const frequencies = TOOLS[16]; +const FREQ_SRC = { + uax29: "https://www.unicode.org/reports/tr29/", + segmenter: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter", + spam: "https://developers.google.com/search/docs/essentials/spam-policies#keyword-stuffing", + excel: "https://learn.microsoft.com/en-us/office/troubleshoot/excel/formulas-to-count-occurrences-in-excel", + counter: "https://docs.python.org/3/library/collections.html#collections.Counter", +}; +const stopwordList = `

${[...STOPWORDS].join(", ")}

`; + +const enFrequency = { + kind: "tool", + tool: "frequency", + script: "word-frequency-counter.js", + lang: "en", + path: frequencies.en.path, + og: "word-frequency-counter", + title: "Word Frequency Counter: Count Repeated Words and Phrases", + ogTitle: "Word frequency counter", + description: "Paste text and see each word ranked by how often it appears, with counts and percentages. Count two- and three-word phrases, skip stop words, export CSV.", + h1: "Count how often each word appears in a text", + lede: "Paste text and every word is ranked by how often it appears, with its count and its share of all words. Switch to two- or three-word phrases, leave out common words like the and of, then copy the table or download it as CSV. Nothing you paste leaves this tab.", + ui: { + toolLabel: "Word frequency counter", + size: "Count", + sizes: [ + ["1", "Words"], + ["2", "2-word phrases"], + ["3", "3-word phrases"], + ], + min: "Minimum length", + minPh: "1", + minHint: "In characters. Shorter words are left out.", + input: "Text", + paste: "Paste from clipboard", + clear: "Clear", + placeholder: "Type or paste the text to analyse.", + output: "Frequency", + copy: "Copy table", + copied: "Copied", + csv: "Download CSV", + rank: "Rank", + word: "Word", + phrase: "Phrase", + count: "Count", + share: "Percent", + empty: "The ranked words appear here.", + zero: "0 words · 0 unique", + options: "Options", + reset: "Reset options", + noscript: "This tool needs JavaScript. In Python, collections.Counter(re.findall(r\"[\\w']+\", text.lower())).most_common(20) lists the 20 most common words.", + messages: { + words: ["word", "words"], + unique: "{n} unique", + uniquePhrases: ["phrase", "phrases"], + shown: "showing the top {n}", + word: "Word", + phrase: "Phrase", + pasted: "Pasted from the clipboard.", + clipboardEmpty: "The clipboard has no text.", + pasteDenied: "The browser did not allow clipboard access. Click the box and press Ctrl+V (Command+V on a Mac).", + pasteUnsupported: "This browser cannot read the clipboard from a button. Click the box and press Ctrl+V (Command+V on a Mac).", + cleared: "Cleared.", + nothingToCopy: "Nothing to copy yet. Paste some text first.", + copied: "{n} rows copied. Paste them into a spreadsheet.", + copyFailed: "Copying failed. Try Download CSV instead.", + downloaded: "CSV downloaded.", + csvHeader: ["Rank", "Word", "Count", "Percent"], + csvHeaderPhrase: ["Rank", "Phrase", "Count", "Percent"], + }, + }, + options: [ + { key: "ignoreCase", label: "Ignore case", hint: "The, THE and the count as one word.", default: true }, + { key: "stopwords", label: "Leave out stop words", hint: "Skips common English words such as the, and, of and it's.", default: false }, + { key: "numbers", label: "Count numbers", hint: "Off leaves out words with no letters, such as 2026 or 3.14.", default: true }, + { key: "turkish", label: "Turkish casing", hint: "Lowercases I to ı and İ to i, so IŞIK and ışık match.", default: false }, + ], + sourceLabel: "Sources", + sections: [ + { + id: "how", + title: "How words are counted", + paragraphs: [ + `Words are split at the ${a(FREQ_SRC.uax29, "Unicode word boundaries (UAX #29)")} that the browser's ${a(FREQ_SRC.segmenter, "Intl.Segmenter")} finds, so the tool works for any language that puts spaces between words. Punctuation, emoji and symbols are not words; #tag counts as tag.`, + "An apostrophe inside a word keeps it whole, so don't and it's are one word each, and a curly ’ counts the same as a straight '. Parts joined by a hyphen with no space count as one word, as in well-known or 2026-12-01. Numbers count as words unless Count numbers is off.", + "With Ignore case on, the list shows each word in lowercase. English rules lowercase I to i; Turkish text needs Turkish casing, where I becomes ı and İ becomes i, or IŞIK and ışık end up as two different words.", + ], + }, + { + id: "phrases", + title: "Phrases, stop words and percentages", + paragraphs: [ + "2-word and 3-word phrases are runs of consecutive words inside one sentence. A phrase never crosses a full stop, so the end of one sentence and the start of the next do not form a phrase.", + `Percent is the count divided by all words in the text, or by all phrases of that length, before any filter. This is what SEO tools call keyword density. There is no target value to aim for: ${a(FREQ_SRC.spam, "Google's spam policies")} name keyword stuffing, repeating words unnaturally to rank, as spam.`, + `Leave out stop words skips the ${STOPWORDS.size} common English words below. For phrases it drops those that start or end with one, like of the or the cat, and keeps those with one in the middle, like end of road.`, + ], + html: stopwordList, + }, + { + id: "code", + title: "Word frequency in Excel and Python", + paragraphs: ["For text that is already in a spreadsheet or a program."], + rows: [ + { + app: "Excel", + lines: [ + `${c('=(LEN(A2)-LEN(SUBSTITUTE(LOWER(A2),"cat","")))/LEN("cat")')} counts how often cat appears in cell A2, in any case.`, + "It counts the letters inside longer words too, so category adds one. Excel has no function that ranks every word in a text.", + ], + sources: [["Formulas to count occurrences in Excel", FREQ_SRC.excel]], + }, + { + app: "Python", + lines: [ + `${c("collections.Counter(re.findall(r\"[\\w']+\", text.lower())).most_common(20)")} lists the 20 most common words with their counts.`, + `${c("[\\w']+")} keeps apostrophes inside words but splits at hyphens, so well-known becomes two words.`, + ], + sources: [["Python docs: collections.Counter", FREQ_SRC.counter]], + }, + ], + note: "Each line was run and checked against the vendor's documentation on 1 December 2026.", + }, + ], + faqTitle: "Questions", + faq: [ + { + q: "How do I count how many times each word appears in a text?", + a: "Paste the text into the box. The table lists every word with the number of times it appears, the most frequent first, and updates as you type. Copy table puts the whole list on your clipboard.", + }, + { + q: "What is keyword density?", + a: "The share of all words that one word or phrase takes up: its count divided by the total number of words, times 100. A word that appears 5 times in a 250-word text has a density of 2%. The Percent column shows this for every word.", + }, + { + q: "Are The and the counted as the same word?", + a: "Yes, while Ignore case is on, which is the default. Turn it off to count The, THE and the separately.", + }, + { + q: "Can I count phrases instead of single words?", + a: "Yes. Choose 2-word phrases or 3-word phrases above the text box. Phrases stay inside one sentence, and with Leave out stop words on, phrases that start or end with words like the or of are skipped.", + }, + { + q: "How do I get the list into Excel or Google Sheets?", + a: "Copy table copies every row, not only the ones shown, with tabs between the columns; paste it into a sheet and each column lands in its own cell. Download CSV saves the same table as a file.", + }, + { + q: "Is the text I paste uploaded or saved?", + a: "No. The counting runs in JavaScript inside this tab, and the page never sends or stores your text. It only remembers the options, in this browser. Page views are counted with Cloudflare Web Analytics, which never sees what you type.", + }, + ], +}; +enFrequency.jsonLd = [toolPage("en", enFrequency, frequencies), faqLd(enFrequency.faq)]; + export const pages = { - list: [enHome, trHome, enTool, trTool, enCompare, trCompare, trKdv, trYas, enDays, enLines, enCase, trCase, enHex, enInvisible, trInvisible, enRepeat, enReverse, enFlip, trFlip, enChmod, enSlug, enSpecial, trSpecial, trCounter], + list: [enHome, trHome, enTool, trTool, enCompare, trCompare, trKdv, trYas, enDays, enLines, enCase, trCase, enHex, enInvisible, trInvisible, enRepeat, enReverse, enFlip, trFlip, enChmod, enSlug, enSpecial, trSpecial, trCounter, enFrequency], notFound: { title: "Page not found: Halit Sever's tools", description: "This page does not exist on tools.halit.org. The list of small browser tools by Halit Sever is one click away, in English and in Turkish.", diff --git a/scripts/og.mjs b/scripts/og.mjs index c65d32b..b1b233a 100644 --- a/scripts/og.mjs +++ b/scripts/og.mjs @@ -126,7 +126,7 @@ ${esc(tool.demoLine1)} ${esc(tool.demoLink)} ${esc(tool.demoLine2)}` } const [enHome, trHome] = pages.list; -const [t, cmp, kdv, yas, days, lines, cases, colors, blanks, repeater, reversal, flips, chmods, slugs, specials, counters] = TOOLS; +const [t, cmp, kdv, yas, days, lines, cases, colors, blanks, repeater, reversal, flips, chmods, slugs, specials, counters, frequencies] = TOOLS; const cards = [ { file: "home", label: "Tools", title: enHome.h1, sub: enHome.lede, url: "tools.halit.org" }, { file: "home-tr", label: "Araçlar", title: trHome.h1, sub: trHome.lede, url: "tools.halit.org/tr" }, @@ -151,6 +151,7 @@ const cards = [ { file: "remove-special-characters", label: "Tools", title: specials.en.name, sub: "Strip punctuation, symbols and accents. Keep what you choose.", url: "tools.halit.org/remove-special-characters", tool: { ...specials.en, name: "" } }, { file: "turkce-karakter-temizleme", label: "Araçlar", title: specials.tr.name, sub: "ç, ğ, ı, ö, ş ve ü harflerini İngilizce karakterlere çevir.", url: "tools.halit.org/tr/turkce-karakter-temizleme", tool: { ...specials.tr, name: "" } }, { file: "karakter-sayaci", label: "Araçlar", title: counters.tr.name, sub: "Kelime, karakter, harf ve cümle sayısı, okuma süresiyle.", url: "tools.halit.org/tr/karakter-sayaci", tool: { ...counters.tr, name: "" } }, + { file: "word-frequency-counter", label: "Tools", title: frequencies.en.name, sub: "Rank every word and phrase by how often it appears.", url: "tools.halit.org/word-frequency-counter", tool: { ...frequencies.en, name: "" } }, { file: "metin-karsilastirma", label: "Araçlar", title: cmp.tr.name, sub: "İki metin arasında eklenen ve silinen satırları, kelimeleri gör.", url: "tools.halit.org/tr/metin-karsilastirma", tool: { ...cmp.tr, name: "" } }, ]; diff --git a/src/frequency.js b/src/frequency.js new file mode 100644 index 0000000..bdbe782 --- /dev/null +++ b/src/frequency.js @@ -0,0 +1,72 @@ +/** Word and phrase frequency for the word frequency counter. Pure functions, so Node tests and the browser share them. */ +import { words } from "./count.js"; + +export const DEFAULTS = Object.freeze({ size: 1, ignoreCase: true, turkish: false, stopwords: false, numbers: true, minLength: 1 }); + +/** Common English function words. Short on purpose: a word only goes here if it rarely tells you what a text is about. */ +export const STOPWORDS = new Set( + ( + "a about above after again against all am an and any are as at be because been before being below between both but by can could did do does doing down during each few for from further had has have having he her here hers herself him himself his how i if in into is it its itself just me more most my myself no nor not now of off on once only or other our ours ourselves out over own same she should so some such than that the their theirs them themselves then there these they this those through to too under until up very was we were what when where which while who whom why will with would you your yours yourself yourselves " + + "i'm i've i'd i'll you're you've you'd you'll he's she's it's we're we've we'd we'll they're they've they'd they'll that's there's what's let's isn't aren't wasn't weren't hasn't haven't hadn't doesn't don't didn't won't wouldn't can't cannot couldn't shouldn't" + ).split(" "), +); + +const HAS_LETTER = /\p{L}/u; +/** Curly and straight apostrophes are the same letter to a reader, so don’t and don't group together. */ +const APOSTROPHES = /[\u2019\u02BC]/g; +const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" }); +const length = (s) => [...graphemes.segment(s)].length; +const sentenceSegmenters = { en: new Intl.Segmenter("en", { granularity: "sentence" }), tr: new Intl.Segmenter("tr", { granularity: "sentence" }) }; +const sentences = (text, locale) => Array.from(sentenceSegmenters[locale].segment(text), (s) => s.segment); + +/** + * Counts words, or phrases of `size` words that sit in the same sentence, and ranks them. + * `share` is the percentage of all words (or all phrases of that size) in the text, counted before any filter. + */ +export function frequency(input, options = {}) { + const o = { ...DEFAULTS, ...options }; + const size = [1, 2, 3].includes(o.size) ? o.size : 1; + const locale = o.turkish ? "tr" : "en"; + const norm = (w) => { + const plain = w.replace(APOSTROPHES, "'"); + if (!o.ignoreCase) return plain; + // English rules lowercase İ to i plus a combining dot; a reader expects a plain i. + return o.turkish ? plain.toLocaleLowerCase("tr") : plain.toLocaleLowerCase("en").replace(/i\u0307/g, "i"); + }; + const stop = (w) => STOPWORDS.has(w.toLocaleLowerCase(locale)); + const keep = (w) => (o.numbers || HAS_LETTER.test(w)) && (o.minLength <= 1 || length(w) >= o.minLength); + + const counts = new Map(); + let total = 0; + let words_ = 0; + const keepMemo = new Map(); + const kept = (w) => { + if (!keepMemo.has(w)) keepMemo.set(w, keep(w)); + return keepMemo.get(w); + }; + for (const sentence of sentences(String(input ?? ""), locale)) { + const list = words(sentence, locale).map(norm); + words_ += list.length; + for (let i = 0; i + size <= list.length; i++) { + total++; + let ok = true; + for (let j = i; j < i + size && ok; j++) ok = kept(list[j]); + if (!ok) continue; + // A phrase that starts or ends with a stop word is a fragment, like "of the" or "the cat". + if (o.stopwords && (stop(list[i]) || stop(list[i + size - 1]))) continue; + const key = size === 1 ? list[i] : list.slice(i, i + size).join(" "); + counts.set(key, (counts.get(key) ?? 0) + 1); + } + } + const collator = new Intl.Collator(locale); + const rows = [...counts] + .map(([text, count]) => ({ text, count, share: total ? (count / total) * 100 : 0 })) + .sort((a, b) => b.count - a.count || collator.compare(a.text, b.text)); + return { words: words_, total, unique: rows.length, rows }; +} + +/** Rows as CSV with a header, quoted where needed, for spreadsheets. */ +export function toCsv(rows, header = ["Rank", "Word", "Count", "Percent"]) { + const cell = (v) => (/[",\n\r]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v)); + return [header, ...rows.map((r, i) => [i + 1, r.text, r.count, r.share.toFixed(2)])].map((line) => line.map(cell).join(",")).join("\r\n"); +} diff --git a/src/word-frequency-counter.js b/src/word-frequency-counter.js new file mode 100644 index 0000000..849fd89 --- /dev/null +++ b/src/word-frequency-counter.js @@ -0,0 +1,200 @@ +/** Wires the word frequency counter. Text stays in this tab; only the options are stored. */ +import { frequency, toCsv, DEFAULTS } from "./frequency.js"; + +const $ = (id) => document.getElementById(id); +const src = $("src"); +const rowsEl = $("rows"); +const table = $("table"); +const empty = $("empty"); +const copyBtn = $("copy"); +const status = $("status"); +const counts = $("counts"); +const min = $("min"); +const t = JSON.parse($("strings").textContent); +const KEY = "tools.word-frequency-counter.options"; +/** Rendering thousands of rows makes typing lag; copy and CSV still carry every row. */ +const SHOWN = 500; + +const boxes = [...document.querySelectorAll("input[data-option]")]; +const radios = [...document.querySelectorAll('input[name="size"]')]; + +/** Options are a per-viewer convenience, so a blocked or empty storage just means defaults. */ +function loadOptions() { + try { + const saved = JSON.parse(localStorage.getItem(KEY) || "{}"); + return { ...DEFAULTS, ...Object.fromEntries(Object.entries(saved).filter(([k, v]) => k in DEFAULTS && typeof v === typeof DEFAULTS[k])) }; + } catch { + return { ...DEFAULTS }; + } +} + +let options = loadOptions(); +let result = frequency(""); + +function paint() { + for (const box of boxes) box.checked = options[box.dataset.option]; + for (const r of radios) r.checked = Number(r.value) === options.size; + min.value = options.minLength > 1 ? String(options.minLength) : ""; +} + +function save() { + try { + localStorage.setItem(KEY, JSON.stringify(options)); + } catch {} +} + +function readOptions() { + const n = Math.floor(Number(min.value)); + options = { + ...Object.fromEntries(boxes.map((b) => [b.dataset.option, b.checked])), + size: Number(document.querySelector('input[name="size"]:checked')?.value ?? 1), + minLength: Number.isFinite(n) && n > 1 ? Math.min(n, 100) : 1, + }; + save(); +} + +const num = (n) => n.toLocaleString("en"); +const plural = (n, [one, many]) => `${num(n)} ${n === 1 ? one : many}`; +const pct = (share) => share.toLocaleString("en", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); + +let statusTimer; +function say(message) { + clearTimeout(statusTimer); + status.textContent = message; + statusTimer = setTimeout(() => (status.textContent = ""), 6000); +} + +function cell(text, cls) { + const td = document.createElement("td"); + if (cls) td.className = cls; + td.textContent = text; + return td; +} + +function update() { + result = frequency(src.value, options); + const frag = document.createDocumentFragment(); + result.rows.slice(0, SHOWN).forEach((r, i) => { + const tr = document.createElement("tr"); + tr.append(cell(num(i + 1), "n rank"), cell(r.text, "word"), cell(num(r.count), "n"), cell(pct(r.share), "n")); + frag.append(tr); + }); + rowsEl.replaceChildren(frag); + $("col-word").textContent = options.size === 1 ? t.word : t.phrase; + table.hidden = result.rows.length === 0; + empty.hidden = result.rows.length > 0; + const parts = [plural(result.words, t.words), t.unique.replace("{n}", num(result.unique))]; + if (result.rows.length > SHOWN) parts.push(t.shown.replace("{n}", num(SHOWN))); + counts.textContent = parts.join(" · "); +} + +/** Segmenting a long text takes a moment, so big pastes wait until typing pauses. */ +let pending; +function schedule() { + clearTimeout(pending); + if (src.value.length < 50000) update(); + else pending = setTimeout(update, 250); +} + +const header = () => (options.size === 1 ? t.csvHeader : t.csvHeaderPhrase); + +/** Tabs between columns, so a paste into Excel or Sheets fills one cell per value. */ +function tsv() { + const clean = (s) => String(s).replace(/[\t\r\n]+/g, " "); + return [header(), ...result.rows.map((r, i) => [i + 1, r.text, r.count, r.share.toFixed(2)])].map((line) => line.map(clean).join("\t")).join("\n"); +} + +/** execCommand keeps the browser's undo history; setRangeText is the fallback where it is gone. */ +function insert(text) { + src.focus(); + src.select(); + let done = false; + try { + done = document.execCommand("insertText", false, text); + } catch {} + if (!done) src.setRangeText(text, src.selectionStart, src.selectionEnd, "end"); + update(); +} + +src.addEventListener("input", schedule); + +$("paste").addEventListener("click", async () => { + if (!navigator.clipboard?.readText) { + say(t.pasteUnsupported); + src.focus(); + return; + } + try { + const text = await navigator.clipboard.readText(); + if (!text) return say(t.clipboardEmpty); + insert(text); + say(t.pasted); + } catch { + say(t.pasteDenied); + src.focus(); + } +}); + +$("clear").addEventListener("click", () => { + src.value = ""; + update(); + src.focus(); + say(t.cleared); +}); + +let copiedTimer; +copyBtn.addEventListener("click", async () => { + if (!result.rows.length) { + say(t.nothingToCopy); + src.focus(); + return; + } + try { + await navigator.clipboard.writeText(tsv()); + } catch { + return say(t.copyFailed); + } + copyBtn.dataset.state = "copied"; + say(t.copied.replace("{n}", num(result.rows.length))); + clearTimeout(copiedTimer); + copiedTimer = setTimeout(() => delete copyBtn.dataset.state, 2000); +}); + +$("csv").addEventListener("click", () => { + if (!result.rows.length) { + say(t.nothingToCopy); + src.focus(); + return; + } + // The byte order mark makes Excel read the file as UTF-8, so accented words survive. + const blob = new Blob(["\uFEFF" + toCsv(result.rows, header())], { type: "text/csv;charset=utf-8" }); + const link = document.createElement("a"); + link.href = URL.createObjectURL(blob); + link.download = options.size === 1 ? "word-frequency.csv" : `phrase-frequency-${options.size}.csv`; + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(link.href), 1000); + say(t.downloaded); +}); + +for (const el of [...boxes, ...radios]) { + el.addEventListener("change", () => { + readOptions(); + update(); + }); +} +min.addEventListener("input", () => { + readOptions(); + update(); +}); + +$("reset").addEventListener("click", () => { + options = { ...DEFAULTS }; + save(); + paint(); + update(); +}); + +paint(); +update(); diff --git a/test/frequency.test.mjs b/test/frequency.test.mjs new file mode 100644 index 0000000..a5dc4aa --- /dev/null +++ b/test/frequency.test.mjs @@ -0,0 +1,49 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { frequency, toCsv, STOPWORDS } from "../src/frequency.js"; + +const top = (text, o) => frequency(text, o).rows.map((r) => [r.text, r.count]); + +test("ranks words by count, ties in alphabetical order", () => { + assert.deepEqual(top("the cat and the hat. The cat sat."), [["the", 3], ["cat", 2], ["and", 1], ["hat", 1], ["sat", 1]]); + const r = frequency("the cat and the hat. The cat sat."); + assert.equal(r.words, 8); + assert.equal(r.total, 8); + assert.equal(r.unique, 5); + assert.equal(r.rows[0].share, 37.5); +}); + +test("case can be kept, and Turkish casing folds I and İ the Turkish way", () => { + assert.deepEqual(top("Apple apple APPLE", { ignoreCase: false }), [["apple", 1], ["Apple", 1], ["APPLE", 1]]); + assert.deepEqual(top("IŞIK ışık İzmir izmir"), [["izmir", 2], ["işik", 1], ["ışık", 1]]); + assert.deepEqual(top("IŞIK ışık İzmir izmir", { turkish: true }), [["ışık", 2], ["izmir", 2]]); +}); + +test("apostrophes keep words whole and curly ones match straight ones", () => { + assert.deepEqual(top("don't don’t İstanbul'da"), [["don't", 2], ["istanbul'da", 1]]); + assert.deepEqual(top("İstanbul'da", { turkish: true }), [["istanbul'da", 1]]); +}); + +test("stop words, numbers and short words can be left out", () => { + assert.deepEqual(top("The cat and the hat", { stopwords: true }), [["cat", 1], ["hat", 1]]); + assert.deepEqual(top("in 2026 we sold 3 cats", { numbers: false, minLength: 3 }), [["cats", 1], ["sold", 1]]); + assert.ok(STOPWORDS.has("the") && STOPWORDS.has("don't") && !STOPWORDS.has("cat")); +}); + +test("phrases stay inside one sentence and drop fragments that start or end with a stop word", () => { + const text = "Word frequency counter. A word frequency counter counts words."; + assert.deepEqual(top(text, { size: 2 }).slice(0, 2), [["frequency counter", 2], ["word frequency", 2]]); + assert.equal(frequency(text, { size: 2 }).total, 7); + assert.deepEqual(top(text, { size: 3 })[0], ["word frequency counter", 2]); + assert.deepEqual(top("the end of the road", { size: 2, stopwords: true }), []); + assert.deepEqual(top("end of road", { size: 3, stopwords: true }), [["end of road", 1]]); +}); + +test("empty text gives no rows", () => { + assert.deepEqual(frequency(""), { words: 0, total: 0, unique: 0, rows: [] }); +}); + +test("CSV quotes cells that need it", () => { + const rows = [{ text: 'say "hi", ok', count: 2, share: 50 }]; + assert.equal(toCsv(rows), 'Rank,Word,Count,Percent\r\n1,"say ""hi"", ok",2,50.00'); +});