Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
Algoritmo para buscar palabras antes y después de la cadena de búsqueda dentro de frases

Supongamos que tengo debajo de la matriz de frases

 const senetences = [ { "text": "And a moment I Yes." }, { "text": "Wait a moment I Yes." }, { "text": "And a moment I Hello, Guenta, trenteuno." }, { "text": "Okay a moment. Hello. Perfect." }, { "text": "And a moment." }, { "text": "And a moment I Hello, Guenta, trenteuno." }, { "text": "Just a moment in Quinta trenteuno." }, { "text": "And a moment in Quinta trenteuno." }, { "text": "Wait a moment I Hello, Guenta, trenteuno." }, { "text": "Just a moment in Quinta trenteuno." } ]

Ahora busco...supongamos moment . Entonces, necesito obtener algunas palabras antes y después del moment exacto de la palabra y su puntaje coincidente en toda la matriz.

Salida de ejemplo

 [ "text": "And a moment", "score": 5, "percent": 50, "text": "moment I Hello", "score": 3, "percent": 30, "text": "moment in Quinta", "score": 3, "percent": 30, "text": "Wait a moment", "score": 2, "percent": 20, "text": "moment I Yes", "score": 2, "percent": 20, "text": "Just a moment", "score": 2, "percent": 20, "text": "Okay a moment", "score": 1, "percent": 10 ]

la score es el número de veces que ocurrió y el percent es el número de veces que ocurrió dividido por el número total de oraciones.

Puedo obtener las palabras después de senetences , pero me quedo atascado después de eso.

 const string = "moment"; const words = []; senetences.map((a) => { const arrayString = a.text.toLowerCase().split(' '); const index = arrayString.indexOf(string.toLowerCase()); words.push(`${arrayString[index - 2]} ${arrayString[index - 1]} ${arrayString[index]}`); words.push(`${arrayString[index]} ${arrayString[index + 1]} ${arrayString[index + 2]}`); })

Después de eso, me quedé atascado en cómo encontrar en la matriz de senetences ahora.

 const output = [] senetences.map((a) => { phrases.map((p) => { const index = a.text.toLowerCase().indexOf(p) if (index !== -1) { output.push(a.text) } }) })
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Puede almacenar las cadenas y los recuentos en un objeto:

 function f(search, length, sentences) { const words = sentences.reduce((acc, { text }) => { const arrayString = text.replaceAll(/\.|,/g, '').split(' '); const index = arrayString.findIndex(el => el.toLowerCase() === search.toLowerCase()); if (index >= length) { const key = arrayString.slice(index - length, index + 1).join(' '); acc[key] = (acc[key] ?? 0) + 1; } if (index < arrayString.length - length) { const key = arrayString.slice(index, index + length + 1).join(' '); acc[key] = (acc[key] ?? 0) + 1; } return acc; }, {}) return Object.entries(words) .map(el => ({ text: el[0], score: el[1], percent: 100 * el[1] / sentences.length })) .sort((l, r) => r.score - l.score); } const sentences = [ {"text": "And a moment I Yes."}, {"text": "Wait a moment I Yes."}, {"text": "And a moment I Hello, Guenta, trenteuno."}, {"text": "Okay a moment. Hello. Perfect."}, {"text": "And a moment."}, {"text": "And a moment I Hello, Guenta, trenteuno."}, {"text": "Just a moment in Quinta trenteuno."}, {"text": "And a moment in Quinta trenteuno."}, {"text": "Wait a moment I Hello, Guenta, trenteuno."}, {"text": "Just a moment in Quinta trenteuno."} ]; console.log(f('moment', 3, sentences));

about 4 years ago · Juan Pablo Isaza Relatório

0

Esta función debería funcionar, agregué un parámetro de precisión para establecer cuántas palabras desea usar en su búsqueda y agregué un código para reemplazar todos los caracteres que no son de texto en las oraciones.

 function searchAndScoreWords(sentences,searchPhrase,precision){ //construct wordsArray const wordsArray = []; sentences.map((sentence) => { const arrayString = sentence.text.toLowerCase().replace(/(\.)|(\,)|(')|(\!)|(\?)/g,'').split(' '); const index = arrayString.indexOf(searchPhrase.toLowerCase()); if(index!==-1){ //if enough words before the search pharse push the words before phrase to array if(index>=precision-1){ let words = []; for(let i=index-precision+1;i<=index;i++){ words.push(arrayString[i]); } wordsArray.push(words.join(' ')); } //if enough words after the search pharse push the words before phrase to array if(index<=arrayString.length-precision){ let words = []; for(let i=index;i<=index+precision-1;i++){ words.push(arrayString[i]); } wordsArray.push(words.join(' ')); } } }) //generate scores let output = []; for(let i=0;i<wordsArray.length;i++){ let occurrences = 0; for(let j=0;j<wordsArray.length;j++){ if(wordsArray[i]===wordsArray[j]){ occurrences++; } } if(!output.find(e=>e.text===wordsArray[i])){ output.push({ text:wordsArray[i], score:occurrences, percent:occurrences/sentences.length*100 }); } } return output; } const sentences = [ { "text": "And a moment, I Yes." }, { "text": "Wait a moment' I Yes." }, { "text": "And a moment? I Hello, Guenta, trenteuno." }, { "text": "Okay a moment. Hello. Perfect." }, { "text": "And a moment." }, { "text": "And a moment! I Hello, Guenta, trenteuno." }, { "text": "Just a moment in Quinta trenteuno." }, { "text": "And a moment in Quinta trenteuno." }, { "text": "Wait a moment I Hello, Guenta, trenteuno." }, { "text": "Just a moment in Quinta trenteuno." } ] console.log(searchAndScoreWords(sentences,"moment",3));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda