Javascript/jQuery 查找文本重复项

标签 javascript jquery text duplicates

您将如何在文本文档中查找重复项。重复项可以是一组连续的单词或句子。句子不必以点结尾。假设页面包含 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/

相关文章:

javascript - 是否有类似强制布局但支持点击事件的 D3 布局引擎

javascript - 无法读取 null 的属性 'complete' - 完成

javascript - JS中根据背景颜色切换元素颜色

javascript - 如何使用JS向html正文添加内容?

jquery - typeerror jquery(...).isotope 不是函数

javascript - 如何使用 Jquery/Javascript/css 在每次点击时动态旋转圆圈?

python - 如何在 Python 中即时预处理文本流?

mysql - 将所有上传的文件存储在一张 MySQL 表中? (文本和 BLOB)

c# - C#从文本文件中读取数字

javascript - 一秒后自动关闭弹出窗口