JavaScript:将句子分成小块



目标

所以,我试着把大句子分解成介于某个阈值之间的小句子。

基本理念

编写一个函数来查找此正则表达式的最佳数字:.{1,20}(?:s|$)

问题

但是我的句子长度各不相同,所以我在使用静态数字时遇到了问题。我需要计算出要使用的正确数字,而不是"0";20〃;在上面的正则表达式中。

标准

找到的数字应该进行优化,以获得最大的句子,165个字符是上限,70个字符是下限。

传递给此函数的所有句子的长度都将超过165个字符。

示例

所以,假设我给它传一个166个字符的句子。这应该返回2个新句子,每个句子大约83个字符。

我认为找到的数字会传递给这个正则表达式:.{1,83}(?:s|$),生成2个没有余数的句子。

结果:['first half of the sentence', 'second half of the sentence']

如果我给它传递一个400个字符的句子,它将返回4个缩短的句子,每个句子大约100个字符。

任何想法都会有所帮助。

好的,下面是我使用TypeScript:的方法

const MAX_LENGTH = 165;
const MIN_LENGTH = 70;
function createChunks(
remainingText: string,
bestBreak: number,
chunks: string[]
): void {
if (remainingText.length > bestBreak) {
// find space closest to bestBreak point
for (let i = bestBreak; i < remainingText.length; i++) {
const charCode = remainingText.charCodeAt(i);
// once found, push chunk to array
if (charCode === 32) {
chunks.push(remainingText.substring(0, i));
// get the remaining text
remainingText = remainingText.substring(i, remainingText.length + 1);
}
}
} else {
chunks.push(remainingText);
}
}
function getChunks(text: string, bestBreak: number): string[] {
const chunks: string[] = [];
let remainingText = text;
createChunks(remainingText, bestBreak, chunks);
return chunks;
}
function createShorterSentences(text: string): string[] {
const sentenceLength = text.length;
let remainder = MAX_LENGTH,
bestBreak = MAX_LENGTH;
// find best breaking point
for (let i = MIN_LENGTH; i < MAX_LENGTH; i++) {
const currRemainder = sentenceLength % i;
if (currRemainder <= remainder) {
remainder = currRemainder;
bestBreak = i;
}
}
return getChunks(text, bestBreak);
}

最新更新