Files
mindfulness/client/src/features/textWrap/core/tokenizeEN.ts
2026-02-10 11:39:33 +08:00

39 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Token } from './types';
/**
* EN tokenize极简派
*
* 口径:
* - tokens 只包含 WORD不生成 SPACE token
* - 标点视为“词内字符”,不额外拆分(例如 "tired."、"Wait..."、"hello—world" 都是一个 token
* - 断点只允许发生在“词与词之间”(由上层生成 breakpoint 时遵守)
*
* start/end 索引以 normalizedText 为基准(建议先调用 normalizeWhitespace
*/
export function tokenizeEN(normalizedText: string): Token[] {
const s = String(normalizedText ?? '');
if (!s) return [];
const tokens: Token[] = [];
// 由于 NORMALIZE 模式下空白都折叠为单空格,这里按空格扫描即可。
// 为了稳健性,也允许出现意外多空格(会跳过空段)。
let i = 0;
const n = s.length;
while (i < n) {
// 跳过空格(或其他空白字符)
while (i < n && /\s/.test(s[i]!)) i++;
if (i >= n) break;
const start = i;
while (i < n && !/\s/.test(s[i]!)) i++;
const end = i;
tokens.push({ text: s.slice(start, end), start, end });
}
return tokens;
}