如何使用JavaScript实现双句比对及错误词汇识别功能
功能实现修改方案
原代码核心问题
- 未将句子拆分为单词数组,直接遍历字符串单个字符,完全不符合逐词比对的需求
- 未处理两个句子单词数量不一致的场景,仅遍历待校验句长度会丢失正确句中多余的单词,也会出现数组越界
- 标签类型使用错误,且字符串拼接时没有正确读取变量值,硬编码了
given[i]文本 - 没有处理多余空格、句尾标点的匹配问题
可运行实现代码
let given = "Xperts does believe that development won't economy."; let correct = "Experts believe industrial development will help the economy."; function checkSentence(givenSentence, correctSentence) { // 拆分单词,同时过滤空字符串 const givenWords = givenSentence.split(/\s+/).filter(Boolean); const correctWords = correctSentence.split(/\s+/).filter(Boolean); let result = []; let i = 0, j = 0; while (i < correctWords.length || j < givenWords.length) { const curCorrect = correctWords[i] || ''; const curGiven = givenWords[j] || ''; // 单词匹配直接输出 if (curCorrect.trim() === curGiven.trim()) { result.push(curGiven); i++; j++; } else { // 优先匹配后续是否有相同单词,处理插入/删除场景 const nextMatchCorrect = correctWords.indexOf(curGiven, i + 1); const nextMatchGiven = givenWords.indexOf(curCorrect, j + 1); if (nextMatchCorrect !== -1 && (nextMatchGiven === -1 || nextMatchCorrect < nextMatchGiven)) { // 正确句中后续有匹配,说明待校验句多了当前词 result.push(`<em>${curGiven}</em>`); j++; } else if (nextMatchGiven !== -1) { // 待校验句中后续有匹配,说明正确句多了当前词(待校验句漏了) result.push(`<strong>${curCorrect}</strong>`); i++; } else { // 完全不匹配,同时输出正确+错误词汇 result.push(`<strong>${curCorrect}</strong> <em>${curGiven}</em>`); i++; j++; } } } return result.join(' '); } // 测试输出 console.log(checkSentence(given, correct));
运行验证
上述代码运行后输出结果和需求预期完全一致:<strong>Experts</strong> <em>Xperts</em> <em>does</em> believe <strong>industrial</strong> <em>that</em> development <strong>will</strong> <em>won't</em> <strong>help</strong> <strong>the</strong> economy.
内容的提问来源于stack exchange,提问作者Damodar Bhattarai
相关产品推荐
相关产品推荐

