2011-08-16 38 views
9

Cách tốt nhất để trích xuất các cụm từ khóa từ một khối văn bản là gì? Tôi đang viết một công cụ để thực hiện trích xuất từ ​​khóa: something like this. Tôi đã tìm thấy một vài thư viện cho Python và Perl để trích xuất n-gram, nhưng tôi đang viết điều này trong Node vì vậy tôi cần một giải pháp JavaScript. Nếu không có bất kỳ thư viện JavaScript nào, ai đó có thể giải thích cách thực hiện điều này để tôi có thể tự viết nó?Trích xuất các cụm từ khóa từ văn bản (1-4 từ ngram)

Trả lời

15

Tôi thích ý tưởng, vì vậy tôi đã thực hiện nó: Xem bên dưới (bình luận mô tả được bao gồm).
Preview tại địa chỉ: http://fiddle.jshell.net/WsKMx/

/*@author Rob W, created on 16-17 September 2011, on request for Stackoverflow (http://stackoverflow.com/q/7085454/938089) 
* Modified on 17 juli 2012, fixed IE bug by replacing [,] with [null] 
* This script will calculate words. For the simplicity and efficiency, 
* there's only one loop through a block of text. 
* A 100% accuracy requires much more computing power, which is usually unnecessary 
**/ 


var text = "A quick brown fox jumps over the lazy old bartender who said 'Hi!' as a response to the visitor who presumably assaulted the maid's brother, because he didn't pay his debts in time. In time in time does really mean in time. Too late is too early? Nonsense! 'Too late is too early' does not make any sense."; 

var atLeast = 2;  // Show results with at least .. occurrences 
var numWords = 5;  // Show statistics for one to .. words 
var ignoreCase = true; // Case-sensitivity 
var REallowedChars = /[^a-zA-Z'\-]+/g; 
// RE pattern to select valid characters. Invalid characters are replaced with a whitespace 

var i, j, k, textlen, len, s; 
// Prepare key hash 
var keys = [null]; //"keys[0] = null", a word boundary with length zero is empty 
var results = []; 
numWords++; //for human logic, we start counting at 1 instead of 0 
for (i=1; i<=numWords; i++) { 
    keys.push({}); 
} 

// Remove all irrelevant characters 
text = text.replace(REallowedChars, " ").replace(/^\s+/,"").replace(/\s+$/,""); 

// Create a hash 
if (ignoreCase) text = text.toLowerCase(); 
text = text.split(/\s+/); 
for (i=0, textlen=text.length; i<textlen; i++) { 
    s = text[i]; 
    keys[1][s] = (keys[1][s] || 0) + 1; 
    for (j=2; j<=numWords; j++) { 
     if(i+j <= textlen) { 
      s += " " + text[i+j-1]; 
      keys[j][s] = (keys[j][s] || 0) + 1; 
     } else break; 
    } 
} 

// Prepares results for advanced analysis 
for (var k=1; k<=numWords; k++) { 
    results[k] = []; 
    var key = keys[k]; 
    for (var i in key) { 
     if(key[i] >= atLeast) results[k].push({"word":i, "count":key[i]}); 
    } 
} 

// Result parsing 
var outputHTML = []; // Buffer data. This data is used to create a table using `.innerHTML` 

var f_sortAscending = function(x,y) {return y.count - x.count;}; 
for (k=1; k<numWords; k++) { 
    results[k].sort(f_sortAscending);//sorts results 

    // Customize your output. For example: 
    var words = results[k]; 
    if (words.length) outputHTML.push('<td colSpan="3" class="num-words-header">'+k+' word'+(k==1?"":"s")+'</td>'); 
    for (i=0,len=words.length; i<len; i++) { 

     //Characters have been validated. No fear for XSS 
     outputHTML.push("<td>" + words[i].word + "</td><td>" + 
      words[i].count + "</td><td>" + 
      Math.round(words[i].count/textlen*10000)/100 + "%</td>"); 
      // textlen defined at the top 
      // The relative occurence has a precision of 2 digits. 
    } 
} 
outputHTML = '<table id="wordAnalysis"><thead><tr>' + 
       '<td>Phrase</td><td>Count</td><td>Relativity</td></tr>' + 
       '</thead><tbody><tr>' +outputHTML.join("</tr><tr>")+ 
       "</tr></tbody></table>"; 
document.getElementById("RobW-sample").innerHTML = outputHTML; 
/* 
CSS: 
#wordAnalysis td{padding:1px 3px 1px 5px} 
.num-words-header{font-weight:bold;border-top:1px solid #000} 

HTML: 
<div id="#RobW-sample"></div> 
*/ 
+0

Tôi đã cập nhật mã để sửa lỗi trong IE8. Lỗi này đã được báo cáo qua thư, tôi đã dán thư và phản hồi của tôi (cung cấp bản sửa lỗi và bao gồm giải thích chi tiết) tại đây: http://pastebin.com/7Edx88Gp. –

+0

đẹp, vài năm sau bạn vẫn đang giúp mọi người –

0

Tôi không biết như một thư viện trong JavaScript nhưng logic là

  1. chia văn bản thành mảng
  2. sau đó sắp xếp và đếm

cách khác chia

  1. vào mảng
  2. tạo mảng phụ
  3. đi qua mỗi mục tương ứng của mảng 1
  4. kiểm tra xem mục hiện tồn tại trong mảng thứ
  5. nếu không tồn tại đẩy nó như là chìa khóa
  6. khác tăng giá trị của một mục có một key = đến mục tìm kiếm. HTH

Ivo Stoykov

+0

doesnt này không làm những gì im muốn b/c nó không giải nén ngrams đa từ ... nó hoạt động cho những từ đơn lẻ chỉ –

+1

xem tại đây -> http: //valuetype.wordpress .com/2011/08/24/keyword-density-with-javascript/đây là mẫu có một từ nhưng có thể dễ dàng mở rộng cho 3 hoặc 4 từ – i100

Các vấn đề liên quan