日本語の 一段落を 「1単語」と 数えてしまう 単語カウント
text.split(/\s+/) で
自己紹介の
これはomiでlen(transcript.split()) >= 2。
僕が
スペース分割はCJKを分割しない
単語カウンタは
const words = text.trim().split(/\s+/).filter(Boolean).length;英語は
"I live in Tokyo".split(/\s+/).length; // 4
"東京に住んでいます".split(/\s+/).length; // 1 ← 文まるごとこの
直し方その1: CJKの文字を別枠で数える
読了時間の
function estimateMinutes(text) {
const cjk = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu;
const cjkChars = (text.match(cjk) ?? []).length;
const latinWords = text.replace(cjk, " ").split(/\s+/).filter(Boolean).length;
return Math.max(1, Math.round(latinWords / 220 + cjkChars / 500));
}いま読んでいる
直し方その2: Intl.Segmenter の word 粒度で区切る
本当に
function countWords(text, locale) {
const seg = new Intl.Segmenter(locale, { granularity: "word" });
let n = 0;
for (const s of seg.segment(text)) if (s.isWordLike) n += 1;
return n;
}
countWords("東京に住んでいます", "ja"); // 1ではなく、語らしき4前後isWordLike が
どの直し方をどこに使うか
| 手法 | CJKを |
ロケールが |
コスト | 向いている |
|---|---|---|---|---|
split(/\s+/) |
数えない |
不要 | ほぼゼロ | 英語だけの |
| CJK文字+英単語の |
数える |
不要 | ほぼゼロ | 読了時間・文字数ゲート・ |
Intl.Segmenter word粒度 |
数える |
必要 | 中 | 本物の |
これらの
どこで止まるか
「単語」は