2012-12-31 2 views
1

페이지의 모든 단어를 식별하고 각 단어의 각 인스턴스가 페이지에 몇 개나 있는지 계산하는 방법을 찾고 있습니다. . 나는 이것을 위해 JavaScript를 사용하고, jQuery는 사용할 필요가 없다.페이지의 모든 단어를 찾는 방법 및 각 단어의 수를 확인하는 방법

UPDATE

이 그것을, 난 아직 두 개 이상의 단어가 함께 병합 된 경우를 얻고 작동하는 것 같군하지만 난 지금까지 무엇을 가지고, 어떤 단서?

if(window.attachEvent) { 
    window.attachEvent("onload", myFunc); 
} else { 
    if(window.onload) { 
     var curronload = window.onload; 
     var newonload = function() { 
      curronload(); 
      myFunc(); 
     }; 
     window.onload = newonload; 
    } else { 
     window.onload = myFunc; 
    } 
} 

function myFunc() { 
    var words = document.body.innerText; 
    words = words.replace(/\n/g, " "); //Remove line breaks 
    words = words.split(" "); 
    var foundWords = new Array(); 
    var counts = new Array(); 
    words.forEach(function(s) { 
     s = s.replace(/^\s+|\s+$/g,''); //Trim 
     s = s.toLowerCase(); //To lower case 
     var index = foundWords.indexOf(s); 
     if(s != \'\') { //If word not blank 
      if(index < 0) { 
       foundWords.push(s); 
       var newindex = foundWords.indexOf(s); 
       counts.push(1); 
      } else { 
       counts[index] += 1; 
      } 
     } 

    }); 

    //Cycle through all found words and log the index, word & count 
    foundWords.forEach(function(s) { 
     var index = foundWords.indexOf(s); 
     console.log(index+" "+s+" "+counts[index]); 
    }); 
} 
+0

지금까지 아무것도 자바 스크립트가 내 가장 강한 요점, 처음에는 자바 스크립트 에서이 일을 어떻게 갈 것이라고 확신하지 못했습니다 – user1448020

+1

1) 모든 텍스트 노드를 선택 2) 단어로 텍스트를 분할 3) 각각의 사건을 계산 낱말 4) 결과를 인쇄하십시오; Javascript 튜토리얼을 읽고 나면 어느 부분이 필요합니까? –

+0

어때 약 3a) 단어 목록을 정렬 3b) 같은 목록에서 인접 항목을 찾기 위해 목록을 스캔 3c) 어딘가에 단어와 함께 저장 –

답변

1

이와 같은 정규 표현식을 사용하십시오.

var words = document.body.textContent || document.body.innerText, 
    matches = words.match(/word/gmi); 

console.log(matches); 
+0

이것은 일종의 작품. 비록 javascript와 일부 div 요소가 뒤늦게 남았습니다. 테스트하려면이 페이지에서 실행하십시오 : javascript : console.log (document.body.textContent) – user1448020

+0

나는 innerText를 사용하여 더 나은 결과를 얻습니다. document.body.innerText가 모든 브라우저 (IE 포함)에서 작동합니까? – user1448020

+0

@ user1448020 확실하지 않지만 Google에서 호환성을 검색 할 수 있습니다. – jeremy

1

다음과 같이 사용할 수 있습니다.

var findWord="What"; 
var totalCount = document.body.innerText.split(findWord).length - 1; 
0

이 솔루션을 연마 할 수 있습니다

<!DOCTYPE html> 
<html> 
<body> 

<p id="demo">Click the button to display the matches.</p> 

<button onclick="myFunction()">Try it</button> 

<script> 
function myFunction() 
{ 
    var str="The rain in SPAIN stays mainly in the plain rain"; 
    var n=str.match(/\S+/g); 

    document.getElementById("demo").innerHTML=n; 

    for(i=0; i < n.length ; i++){ 
     r = str.match(new RegExp(n[i], 'g')); 
     document.getElementById("demo").innerHTML+= '<br>'+ n[i] +' = ' + r.length ; 
    } 
} 
</script> 

</body> 
</html> 
4

난이 (다소 비꼬는) 덧글 먼저 기본적인 자바 스크립트에 몇 가지 조사를 촉구에 동의 인정합니다. 나는 이걸로 쪼개는 것이 재미있을 거라 생각했는데, 그래서 여기에 내가 생각해 낸 것이있다.

단어 목록과 빈도를 콘솔에 출력합니다.

물론 결과를 필터링하여 약간 더 멋지게 만들고 싶지만 다른 질문입니다.

var words = []; 

var walkDOM = function (node, func) { 
    func(node); 
    node = node.firstChild; 
    while(node) { 
     walkDOM(node, func); 
     node = node.nextSibling; 
    } 

}; 

walkDOM(document.body, function (node) { 

    if (node.nodeName === '#text') { 
     var text = node.textContent; 

     text = text.replace(/[^A-Za-z]/g, ' '); 

     text = text.split(' '); 

     if (text.length) { 

      for (var i = 0, length = text.length; i < length; i += 1) { 
       var matched = false, 
        word = text[i]; 

       for (var j = 0, numberOfWords = words.length; j < numberOfWords; j += 1) { 
        if (words[j][0] === word) { 
         matched = true; 
         words[j][1] += 1; 
        } 
       } 

       if (!matched) { 
        words.push([word, 1]); 
       } 

      } 
     } 
    } 
}); 

var displayWordList = function (words) { 
    for (var i = 0, length = words.length; i < length; i += 1) { 
     console.log(words[i][0], words[i][1]); 
    } 
}; 

displayWordList(words); 
​ 

http://jsfiddle.net/E7qSb/

자바 스크립트에서 더글라스 크록 포드의 walkDOM 예를 사용 : 좋은 부품. 하지만 document.body의 innerText 속성이 있다는 것을 다른 사람들로부터 봅니다. 음, 더 쉬워.

단어 개수를 유지하는 방법이 질문자에게 유용 할 수 있으므로이 답을 남겨두고 있습니다.

관련 문제