JS 代码实现英文小说摘录文本匹配原文
使用 JavaScript 代码可以实现通过摘录文本在英文小说原文中找到匹配内容的功能。以下代码示例展示了字符串匹配和相似度算法的使用:/n/njavascript/n// 小说原文/nconst novelText = 'Once upon a time, there was a beautiful princess named Cinderella. She lived with her stepmother and two stepsisters in a small cottage.';/n/n// 摘录文本/nconst excerpt = 'Once upon a time, there was a beautiful princess named Cinderella. She lived with her stepmother and two stepsisters.';/n/n// 移除标点符号和空格,并将字符串转换为小写/nfunction preprocessText(text) {/n return text.replace(/[^/w/s]/g, '').toLowerCase();/n}/n/n// 计算两个字符串的相似度/nfunction calculateSimilarity(str1, str2) {/n const set1 = new Set(str1.split(' '));/n const set2 = new Set(str2.split(' '));/n const intersection = new Set([...set1].filter(x => set2.has(x)));/n const union = new Set([...set1, ...set2]);/n return intersection.size / union.size;/n}/n/n// 查找小说原文/nfunction findOriginalText(novelText, excerpt) {/n const novelWords = preprocessText(novelText).split(' ');/n const excerptWords = preprocessText(excerpt).split(' ');/n /n let startIndex = -1; // 小说原文起始索引/n let endIndex = -1; // 小说原文结束索引/n /n for (let i = 0; i <= novelWords.length - excerptWords.length; i++) {/n const similarity = calculateSimilarity(novelWords.slice(i, i + excerptWords.length).join(' '), excerpt);/n /n if (similarity > 0.8) { // 设置相似度阈值/n startIndex = i;/n endIndex = i + excerptWords.length - 1;/n break;/n }/n }/n /n if (startIndex !== -1 && endIndex !== -1) {/n return novelWords.slice(startIndex, endIndex + 1).join(' ');/n }/n /n return '未找到匹配的文本。';/n}/n/n// 测试/nconst originalText = findOriginalText(novelText, excerpt);/nconsole.log(originalText);/n/n/n请注意,这只是一个简单的示例代码,可能无法处理一些特殊情况。你可以根据实际需求进行修改和优化。
原文地址: https://www.cveoy.top/t/topic/qtbO 著作权归作者所有。请勿转载和采集!