【问题标题】:How to find the same words in two different textarea and count them?如何在两个不同的文本区域中找到相同的单词并计算它们?
【发布时间】:2018-01-05 20:50:31
【问题描述】:

我有多个包含数百个数据的 Excel 列。我想在这些列中找到相同的单词。例如, 第一栏:dog rat catch act some cat fork apple, 第二列:fork dog lamp song apple some hymn candle等,输出为“dog, some, fork, apple”。

我从Intersecting texts to find common words 这个线程中找到了这段代码。它适用于字符串,但不适用于文本区域和输入。我试图针对我的问题对其进行修改,但是失败了。

提前致谢。

var t1 = document.getElementById('first').value;
var t2 = document.getElementById('second').value;
function intersect() {
    var set = {};
    [].forEach.call(arguments, function(a,i){
      var tokens = a.match(/\w+/g);
      if (!i) {
        tokens.forEach(function(t){ set[t]=1 });
      } else {
        for (var k in set){
          if (tokens.indexOf(k)<0) delete set[k];
        }
      }
    });
    return Object.keys(set);
 }

 console.log(intersect(t1, t2));
<textarea id="first"></textarea>
<textarea id="second"></textarea>

【问题讨论】:

  • “我试图针对我的问题对其进行修改,但失败了。” - 你尝试了什么?什么失败了?

标签: javascript html


【解决方案1】:

这是我的尝试:

function update(){
  var result = compare(
    document.getElementById("first").value,
    document.getElementById("second").value,
    " " //Space
  );
  console.log(result);
}
  
function compare(haystack, needles, separator) {
  var result = new Array();
  var HaystackArray = haystack.split(separator);
  var NeedlesArray = needles.split(separator);
  HaystackArray.forEach(function(needle) {
    if(!NeedlesArray.includes(needle))
      return;
    //Remove that if you want to allow words to be in the result multiple times
    if(result.includes(needle))
      return;
    
    result.push(needle);
  });
  return result;
}
<textarea id="first" onChange='update()'>Lorem ipsum dolor sit amet, consectetur adipiscing elit</textarea>
<textarea id="second" onChange='update()'>Lorem ipsum in hac habitasse platea dictumst consectetur dolor</textarea>

【讨论】:

  • 它可以工作,但它不是动态的。当我尝试粘贴文本时它不起作用。
  • 现在试试,我已经更新了代码。每次您关注 textarea 时,它都应该打印新结果。
【解决方案2】:
 function intersect() {
        let arr1 = t1.split("/*you can split by comma or whitespace*/");
        let arr2 = t2.split("");
        let result = [];
        for (let i = 0; i < arr1.length; i +=1) {
            for (let i1 = 0; i1 < arr2.length; i1 +=1 {
                if (arr1[i] === arr2[i1]) {
                    result.push(arr[i]);
                    break;
                }
            }
        }
        return result;
    }

试试这个。

【讨论】:

    猜你喜欢
    • 2013-08-28
    • 2013-04-29
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多