🌐
WebAssembly / npm
kham-wasm นำการตัดคำภาษาไทยมาสู่เบราว์เซอร์และ Node.js โดยไม่ต้องใช้เซิร์ฟเวอร์ ไฟล์ WASM ขนาดประมาณ 300 KB และมี dictionary ในตัว
1
ติดตั้ง
npm install kham-wasm 2
Browser — ES module
import init และเรียกครั้งเดียวเพื่อโหลดไฟล์ .wasm จากนั้นใช้ segment() หรือ segment_tokens() ได้เลย
import init, { segment, segment_tokens } from 'kham-wasm';
await init(); // โหลด WebAssembly module
const words = segment("กินข้าวกับปลา");
console.log(words);
// ["กิน", "ข้าว", "กับ", "ปลา"] 3
Lazy loading (แนะนำ)
โหลด WASM ในพื้นหลังเพื่อไม่ให้บล็อคการแสดงผลหน้าเว็บ
let kham: any = null;
async function getKham() {
if (kham) return kham;
const mod = await import('kham-wasm');
await mod.default();
kham = mod;
return kham;
}
// โหลดล่วงหน้าในพื้นหลัง
getKham().catch(console.error); 4
ตรวจสอบคำสะกด
spell_suggestions(word, maxN) ค้นหา candidate ใน dictionary ที่มี edit distance ≤ 2 จัดอันดับด้วย lk82 phonetic similarity และ TNC corpus frequency
import init, { spell_suggestions } from 'kham-wasm';
await init();
// spell_suggestions(word, maxN) → SpellSuggestion[]
const suggs = spell_suggestions("กีนข้าว", 5);
for (const s of suggs) {
console.log(s.word, 'edit:', s.edit_distance,
'soundex:', s.soundex_match, 'freq:', s.freq_score);
}
// กินข้าว edit: 1 soundex: true freq: …
// SpellSuggestion: .word .edit_distance .soundex_match .freq_score 5
สกัดคำสำคัญ
extract_keywords(text, maxN) คืนคำที่โดดเด่นที่สุด คะแนน TF × inverse-corpus-frequency ตัด stopword ออกโดยอัตโนมัติ
import init, { extract_keywords } from 'kham-wasm';
await init();
// extract_keywords(text, maxN) → Keyword[]
const text = "นักวิทยาศาสตร์ค้นพบดาวเคราะห์ใหม่ในระบบสุริยะ " +
"ดาวดวงนี้โคจรอยู่ใกล้ดาวเคราะห์น้อย";
const keywords = extract_keywords(text, 5);
for (const kw of keywords) {
console.log(kw.word, 'score:', kw.score.toFixed(4), 'count:', kw.count);
}
// Keyword: .word .score .count