(
texts: string[],
locale: SupportedLocale,
options: BatchSegmentOptions = {}
)
| 174 | * 批量分词并统计词频 |
| 175 | */ |
| 176 | export function batchSegmentWithFrequency( |
| 177 | texts: string[], |
| 178 | locale: SupportedLocale, |
| 179 | options: BatchSegmentOptions = {} |
| 180 | ): BatchSegmentResult { |
| 181 | const { |
| 182 | minLength, |
| 183 | minCount = 2, |
| 184 | topN = 100, |
| 185 | posFilterMode, |
| 186 | customPosTags, |
| 187 | enableStopwords, |
| 188 | dictType, |
| 189 | excludeWords, |
| 190 | } = options |
| 191 | const wordFrequency = new Map<string, number>() |
| 192 | const excludeSet = excludeWords?.length ? new Set(excludeWords.map((w) => w.toLowerCase())) : null |
| 193 | |
| 194 | for (const text of texts) { |
| 195 | const words = segment(text, locale, { minLength, posFilterMode, customPosTags, enableStopwords, dictType }) |
| 196 | for (const word of words) { |
| 197 | if (excludeSet && excludeSet.has(word.toLowerCase())) continue |
| 198 | wordFrequency.set(word, (wordFrequency.get(word) || 0) + 1) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | const filtered = new Map<string, number>() |
| 203 | let totalWords = 0 |
| 204 | for (const [word, count] of wordFrequency) { |
| 205 | if (count >= minCount) { |
| 206 | filtered.set(word, count) |
| 207 | totalWords += count |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | const sorted = [...filtered.entries()].sort((a, b) => b[1] - a[1]).slice(0, topN) |
| 212 | return { words: new Map(sorted), uniqueWords: filtered.size, totalWords } |
| 213 | } |
| 214 | |
| 215 | /** |
| 216 | * 中文单遍分词:一次 jieba.tag 同时产出词频与词性统计。 |
no test coverage detected