Javascript 如何处理一个句子数组以返回另一个数组,其中最长的句子少于x个字符?

Javascript 如何处理一个句子数组以返回另一个数组,其中最长的句子少于x个字符?,javascript,Javascript,我有一系列不同长度的句子。让我们假设它看起来像这样: sentences = [ "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts." "I never thought that would happen!", "This one?", "No, no, that one.", "Ok

我有一系列不同长度的句子。让我们假设它看起来像这样:

sentences = [
   "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts."
   "I never thought that would happen!",
   "This one?",
   "No, no, that one.",
   "Okay but please ensure your sentences are long enough to be split when longer than 100 characters, although some could be too short as well.",
   "This is also a random text like all others",
]
我需要的是在第一个句子的基础上构建另一个句子数组,每个元素尽可能大,但不超过100个字符。相反,超过100个字符的句子应该分成更小的句子块。因此,如果原始数组中有5个句子的长度如下:

[0] => 150
[1] => 10
[2] => 35
[3] => 5
[4] => 70
然后,新数组应具有以下元素长度:

[0] => 100 // Split since longer than 100 chars
[1] => 100 // 50 carried forward from [0] + 10 + 35 + 5
[2] => 70
请注意,我不想在此过程中拆分单词

我尝试过以下方法:

let para = [];

let index = 0;
let i = 0;
while(nsentences[i]) {
  let bigsentence = nsentences[i];
  let x = i + 1;

  let bs = bigsentence + ' ' + nsentences[x];
  console.log(bs);
  while(bs.length < 140){
    console.log(bs);

  }


  while(x) {
    let bs = bigsentence + ' ' + nsentences[x];
    if(bs.length < 100) {
      bigsentence += ' ' + nsentences[x];
      x++;
      i += x;
    } else {
      para.push(bigsentence);
      break;
    }
  }
}
让para=[];
设指数=0;
设i=0;
while(n内容[i]){
让bigstence=n内容[i];
设x=i+1;
设bs=bigstation+'''+n句子[x];
控制台日志(bs);
而(英国标准长度<140){
控制台日志(bs);
}
while(x){
设bs=bigstation+'''+n句子[x];
如果(bs.长度<100){
大句子+=''+n句子[x];
x++;
i+=x;
}否则{
段落推送(大句子);
打破
}
}
}

但正如你所预料的,它不起作用。该代码段只返回连接的前两个句子的无限循环

按空格连接句子数组,然后用正则表达式匹配最多100个字符,并在后跟空格的位置(或字符串的结尾)结束,以确保最后匹配的字符位于单词的结尾:

const语句=[
“在遥远的地方,在“山脉”这个词的后面,在远离伏卡利亚和辅音的国家,那里居住着盲文。”,
“我从没想过会发生这种事!”,
“这个?”,
“不,不,那个。”,
“好的,但是请确保你的句子足够长,当长度超过100个字符时可以拆分,尽管有些句子也可能太短。”,
“与所有其他文本一样,这也是一个随机文本”,
];
常量词=句子。连接(“”);
常量输出=words.match(/\S.{1,99}(?=|$)/g);

控制台日志(输出)这里是一种稍微不同的方法,它依赖于函数生成器

由于我不完全理解您的输出有多有限,此解决方案是:

  • 获取由空格连接的单个字符串
  • 用空格分割所述字符串

  • 产生一个长度为i.length)的句子我使用简单的循环完成了这项工作。算法的工作原理如下

  • 创建一个包含所有单词的数组
  • 记下每个单词,确保不会达到极限
  • 达到此限制时创建新行
  • 没有单词时返回行
  • const语句=[
    “在遥远的地方,在“山脉”这个词的后面,在远离伏卡利亚和辅音的国家,那里居住着盲文。”,
    “我从没想过会发生这种事!”,
    “这个?”,
    “不,不,那个。”,
    “好的,但是请确保你的句子足够长,当长度超过100个字符时可以拆分,尽管有些句子也可能太短。”,
    “与所有其他文本一样,这也是一个随机文本”
    ];
    常量长度=句子=>句子.map(s=>s.length);
    常量词=句子。连接(“”)。拆分(“”);
    const takeWords=(字符限制,单词)=>{
    var currlinelength,lines=[],j=0;
    for(设i=0;i++){
    currlinelength=0;
    行[i]=“”;
    while(true){
    如果(j>=单词长度){
    //删除最后一个空格
    返回lines.map(l=>l.trim());
    }
    if((currlinelength+字[j].length)>charlimit){
    打破
    }
    行[i]+=字[j]+';
    currlinelength+=1+字[j]。长度;
    j++;
    }
    }
    };
    console.log(长度(句子));
    结果=字数(100字);
    控制台日志(结果);
    
    控制台日志(长度(结果))您也可以试试这个:

    
    句子=[
    “在遥远的地方,在“山脉”这个词的后面,在远离伏卡利亚和辅音的国家,那里居住着盲文。”,
    “我从没想过会发生这种事!”,
    “这个?”,
    “不,不,那个。”,
    “好的,但是请确保你的句子足够长,当长度超过100个字符时可以拆分,尽管有些句子也可能太短。”,
    “与所有其他文本一样,这也是一个随机文本”
    ]
    函数计算(长度){
    var returnedArray=[];
    指数=0;
    连接=句子。连接(“”);
    做{
    如果(关节长度>长度)
    {
    返回数组[索引]=关节切片(0100);
    索引++;
    接头=接头切片(101,接头长度);
    }
    }while(节理长度>长度);
    if(接头长度)
    {
    返回阵列[索引]=接头;
    }
    $.each(返回数组,(键,值)=>{
    console.log(value.length);
    });
    }
    点击
    
    “严格使用”;
    常量句子=[
    “在很远的地方,在“山脉”这个词的后面,在远离沃卡利亚和辅音的国家,那里住着盲文。”,
    “我从没想过会发生这种事!”,
    “这个?”,
    “不,不,那个。”,
    “好的,但是请确保你的句子足够长,当长度超过100个字符时可以拆分,尽管有些句子也可能太短。”,
    “这也是一个随机文本,就像所有其他文本一样”,
    ];
    功能小于100(arr){
    常量结果=[];
    用于(arr的施工项目){
    if(item.textLength<100&&item.used!=true){
    结果:推送(项目);
    }
    }
    返回结果;
    }
    功能(句子){
    让结果=[];
    for(句子的常量){
    如果(句子长度>100){
    结果.推送(新句子(句子.文本.切片(0,100),假,100));
    const lengthLeft=句子.textLength-100;
    常数小于等于100(句);
    让计数器=长度左;
    let required=[];
    用于(常数项较少){
    如果(计数器+item.textLength p.textLength<100);
    如果(resultLeft.length>=2){
    for(设i=0;i"use strict";
    const sentences = [
        'Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.',
        'I never thought that would happen!',
        'This one?',
        'No, no, that one.',
        'Okay but please ensure your sentences are long enough to be split when longer than 100 characters, although some could be too short as well.',
        'This is also a random text like all others',
    ];
    function lessThan100(arr) {
        const result = [];
        for (const item of arr) {
            if (item.textLength < 100 && item.used != true) {
                result.push(item);
            }
        }
        return result;
    }
    function perform(sentences) {
        let result = [];
        for (const sentence of sentences) {
            if (sentence.textLength > 100) {
                result.push(new Sentence(sentence.text.slice(0, 100), false, 100));
                const lengthLeft = sentence.textLength - 100;
                const less = lessThan100(sentences);
                let counter = lengthLeft;
                let required = [];
                for (const item of less) {
                    if (counter + item.textLength <= 100) {
                        required.push(item);
                        item.setUsed();
                        counter += item.textLength;
                    }
                }
                let str = sentence.text.slice(100, sentence.textLength);
                for (const r of required) {
                    r.setUsed();
                    str += r.text;
                }
                result.push(new Sentence(str, false, str.length));
            }
        }
        for (const item of sentences) {
            if (item.used == false && item.textLength <= 100) {
                result.push(item);
            }
        }
        result = result.sort((a, b) => {
            return b.textLength - a.textLength;
        });
        const resultLeft = result.filter(p => p.textLength < 100);
        if (resultLeft.length >= 2) {
            for (let i = 0; i < resultLeft.length; i++) {
                const sentence = resultLeft[i];
                resultLeft.splice(i, 1);
                const requiredLength = 100 - sentence.textLength;
                const less = lessThan100(resultLeft);
                let counter = sentence.textLength;
                let required = [];
                for (const item of less) {
                    if (counter + item.textLength < 100) {
                        required.push(item);
                        item.setUsed();
                        counter += item.textLength;
                    }
                    else if (counter < 100) {
                        const requiredLength = 100 - counter;
                        required.push(new Sentence(item.text.slice(0, requiredLength), false, requiredLength));
                        item.text = item.text.slice(requiredLength, item.textLength);
                        item.textLength = item.text.length;
                    }
                }
                let str = sentence.text;
                for (const r of required) {
                    r.setUsed();
                    str += r.text;
                }
                const newStr = new Sentence(str, false, str.length);
                const index = result.findIndex(p => p.id === sentence.id);
                result[index] = newStr;
            }
        }
        return result;
    }
    class Sentence {
        constructor(text, used, textLength) {
            this.id = ++Sentence.Ids;
            this.text = text;
            this.textLength = textLength;
            this.used = used;
        }
        setUsed() {
            this.used = true;
        }
    }
    Sentence.Ids = 0;
    function ToFunctionUseful(arr) {
        const result = [];
        for (const item of arr) {
            result.push(new Sentence(item, false, item.length));
        }
        return result;
    }
    const result = perform(ToFunctionUseful(sentences));
    console.log(result, result.map(p => p.textLength));
    console.log(sentences.map(p => p.length));