Сравните два предложения и определите неправильные слова в javascript

#javascript

Вопрос:

Я хочу сравнить два предложения. Вот пример:

Правильно: Эксперты считают, что промышленное развитие поможет экономике.
Учитывая: Xperts действительно считает, что развитие не приведет к экономии.

Ожидаемые результаты:

считают ли эксперты Xperts , что промышленное развитие не поможет экономике?

Я попытался сравнить строку, разделив оба слова и проверив их.

 let given= "Xperts does believe that development won't economy.";
let correct= "Experts believe industrial development will help the economy.";

function checkSentence(given,correct){
    let final='';
        for(i=0; i<given.length; i  ){
            if(given[i].trim()==correct[i].trim()){
                final  = given[i] ' ';
            }else{
                final  = "<i>given[i]</i> <b>correct[i]</b>";
            }
        }
        return final;
}
 

Комментарии:

1. Проверьте github.com/kpdecker/jsdiff

2. Я этого не понимаю. Если это просто «замена», то почему бы и нет if given.match(/Xperts does believe that development won't economy/) given = correct ? Или вы хотите написать предложение по заданному предложению?

3. Ты не разбиваешь предложения на слова?

Ответ №1:

Я бы решил проблему рекурсивно, выполнив следующие шаги:

  1. Попробуйте найти наиболее близкое совпадающее слово в каждом предложении
  2. Если найдено совпадение: разделите каждое предложение на соответствующее слово и запустите одну и ту же функцию с каждой стороны
  3. Если совпадение не найдено: оба предложения не имеют ничего общего, и вы можете вернуть каждое предложение в нужном формате

Примечание: Я начинаю и пытаюсь найти самое длинное совпадающее слово, потому что это наиболее показательно для структуры предложения, а не для поиска » это » и «и»

 const correct= "Experts believe industrial development will help the economy.";
const given= "Xperts does believe development that won't economy.";

const correctArray = correct.split(" ")
const givenArray = given.split(" ")

// Returns [correctIndex, givenIndex] if match found or [-1, -1] if no match found
function findIndexOfLongestMatchingWord(correctArray, givenArray) {

  // Create an array of word length and its index for the correct word array 
  const correctWordLengthIndexArray = correctArray.map((word, index) => [word.length, index]).sort(([length1, index1], [length2, index2]) => length2 - length1)

  for(let matchingIndex = 0; matchingIndex < correctArray.length; matchingIndex  ) {
    
    const correctArrayIndex = correctWordLengthIndexArray[matchingIndex][1]
    const correctArrayWord = correctArray[correctArrayIndex]
    const foundIndexOfGivenWord = givenArray.findIndex(givenWord => givenWord === correctArrayWord)

    if(foundIndexOfGivenWord != -1) return [correctArrayIndex, foundIndexOfGivenWord];
  }

  return [-1,-1]
}

function formatCorrectArray(correctArray) {
  return correctArray.length == 0 ? "" : `<b>${correctArray.join(" ")}</b>`
}

function formatGivenArray(givenArray) {
  return givenArray.length == 0 ? "" : `<i>${givenArray.join(" ")}</i>`
}


function findDifferenceRecursively(correctArray, givenArray) {

  // If either array empty there is nothing to compare, return each one formatted
  if(correctArray.length == 0 || givenArray.length == 0) {
    return formatCorrectArray(correctArray)   formatGivenArray(givenArray)
  }

  const [correctIndex, givenIndex] = findIndexOfLongestMatchingWord(correctArray, givenArray);

  if (correctIndex != -1) {
    // Split each string at their index and run find difference on each side of the indexes;
    const leftCorrect = correctArray.slice(0, correctIndex)
    const rightCorrect = correctArray.slice(correctIndex   1)

    const leftGiven = givenArray.slice(0, givenIndex)
    const rightGiven = givenArray.slice(givenIndex   1)

    // Run function on words on each side
    return findDifferenceRecursively(leftCorrect, leftGiven)   ` ${correctArray[correctIndex]} `   findDifferenceRecursively(rightCorrect, rightGiven)
  } else {
    return formatCorrectArray(correctArray)   formatGivenArray(givenArray)
  }
}

const result = findDifferenceRecursively(correctArray, givenArray)

// Returns "<b>Experts</b><i>Xperts does</i> believe <b>industrial</b> development <b>will help the</b><i>that won't</i> economy. "
console.log(result)