您将如何在文本文档中查找重复项。重复项可以是一组连续的单词或句子。句子不必以点结尾。假设页面包含 200 行的文档,其中 2 个句子相同,我们希望在单击“检查重复按钮”时将这 2 个句子突出显示为重复。
最佳答案
有趣的问题——这是我可能如何做到这一点的想法:http://jsfiddle.net/SaQAs/1/ — 无论如何都没有优化!
var text = $('p').text(),
words = text.split(' '),
sortedWords = words.slice(0).sort(),
duplicateWords = [],
sentences = text.split('.'),
sortedSentences = sentences.slice(0).sort(),
duplicateSentences = [];
for (var i=0; i<sortedWords.length-1; i++) {
if (sortedWords[i+1] == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
duplicateWords = $.unique(duplicateWords);
for (var i=0; i<sortedSentences.length-1; i++) {
if (sortedSentences[i+1] == sortedSentences[i]) {
duplicateSentences.push(sortedSentences[i]);
}
}
duplicateSentences = $.unique(duplicateSentences);
$('a.words').click(function(){
var highlighted = $.map(words, function(word){
if ($.inArray(word, duplicateWords) > -1)
return '<span class="duplicate">' + word + '</span>';
else return word;
});
$('p').html(highlighted.join(' '));
return false;
});
$('a.sentences').click(function(){
var highlighted = $.map(sentences, function(sentence){
if ($.inArray(sentence, duplicateSentences) > -1)
return '<span class="duplicate">' + sentence + '</span>';
else return sentence;
});
$('p').html(highlighted.join('.'));
return false;
});
更新 1
这个找到相同单词的序列:http://jsfiddle.net/YQdk5/1/从这里应该不难,例如比较时忽略片段末尾的任何标点符号——您只需编写自己的 inArray
方法版本即可。
var text = $('p').text(),
words = text.split(' '),
sortedWords = words.slice(0).sort(),
duplicateWords = []
highlighted = [];
for (var i=0; i<sortedWords.length-1; i++) {
if (sortedWords[i+1] == sortedWords[i]) {
duplicateWords.push(sortedWords[i]);
}
}
duplicateWords = $.unique(duplicateWords);
for (var j=0, m=[]; j<words.length; j++) {
m.push($.inArray(words[j], duplicateWords) > -1);
if (!m[j] && m[j-1])
highlighted.push('</span>');
else if (m[j] && !m[j-1])
highlighted.push('<span class="duplicate">');
highlighted.push(words[j]);
}
$('p').html(highlighted.join(' '));
更新 2
我的 regex-fu 很弱,但是这个(相当困惑!)版本似乎工作正常:http://jsfiddle.net/YQdk5/2/ — 我很确定可能有更好的方法来做到这一点,但现在我必须别管它了! :D——祝你好运!
更新 3
想想看,我觉得上次更新的代码没什么好用的。这就是我删除它的原因。您仍然可以在这里找到它:http://jsfiddle.net/YQdk5/2/ 要点是使用正则表达式来匹配单词,大致如下:
/^word(\.?)$/
关于Javascript/jQuery 查找文本重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5046145/