Skip to content

Instantly share code, notes, and snippets.

@prykon
Created October 24, 2019 11:26
Show Gist options
  • Save prykon/e78877a156aa68d1ef0a8ca741c2ee46 to your computer and use it in GitHub Desktop.
Save prykon/e78877a156aa68d1ef0a8ca741c2ee46 to your computer and use it in GitHub Desktop.
Extract keyword n-grams from a Google SERP
var stopwords = [
'about', 'after', 'all', 'also', 'am', 'an', 'and', 'another', 'any', 'are', 'as', 'at', 'be',
'because', 'been', 'before', 'being', 'between', 'both', 'but', 'by', 'came', 'can',
'come', 'could', 'did', 'do', 'each', 'for', 'from', 'get', 'got', 'has', 'had',
'he', 'have', 'her', 'here', 'him', 'himself', 'his', 'how', 'if', 'in', 'into',
'is', 'it', 'like', 'make', 'many', 'me', 'might', 'more', 'most', 'much', 'must',
'my', 'never', 'now', 'of', 'on', 'only', 'or', 'other', 'our', 'out', 'over',
'said', 'same', 'see', 'should', 'since', 'some', 'still', 'such', 'take', 'than',
'that', 'the', 'their', 'them', 'then', 'there', 'these', 'they', 'this', 'those',
'through', 'to', 'too', 'under', 'up', 'very', 'was', 'way', 'we', 'well', 'were',
'what', 'where', 'which', 'while', 'who', 'with', 'would', 'you', 'your', 'a', 'i', 's']
function nGrams(sentence, limit) {
ns = [1,2,3,4]; var grams = {};
var words = sentence.replace(/(?:https?|ftp):\/\/[\n\S]+/g, '').toLowerCase().split(/\W+/).filter(function (value) {return stopwords.indexOf(value.toLowerCase()) === -1})
for (n of ns){
var total = words.length - n;
for(var i = 0; i <= total; i++) {
var seq = '';
for (var j = i; j < i + n; j++) { seq += words[j] + ' ';}
if (seq.trim().length < 3) {continue;}else{seq = seq.trim()}
grams[seq] = seq in grams ? grams[seq] + 1 : 1;
}
}
var sort = Object.keys(grams).sort(function(a,b){return grams[b]-grams[a]});
for (s of sort){ if (grams[s] < limit){break;} console.log(s, ':', grams[s]);}
}
var gtext = document.all.search.innerText
var ng = nGrams(gtext, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment