xxxxxxxxxx
52
// Word Counting
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/CodingChallenges/040.1-wordcounts-p5.html
let txt;
let counts = {};
let keys = [];
let ignore = ['a','is','of'];
function preload() {
txt = loadStrings('rainbow.txt');
}
function setup() {
let allwords = txt.join("\n");
let tokens = allwords.split(/\W+/);
for (let i = 0; i < tokens.length; i++) {
let word = tokens[i].toLowerCase();
//if (/\w{5,}/.test(word)) {
if (!ignore.includes(word)) {
if (counts[word] === undefined) {
counts[word] = 1;
keys.push(word);
} else {
counts[word] = counts[word] + 1;
}
}
}
keys.sort(compare);
function compare(a, b) {
var countA = counts[a];
var countB = counts[b];
return countB - countA;
}
createCanvas(800, 600);
background(200);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
textSize(counts[key] * 0.5);
let w = textWidth(key);
let h = textAscent() - textDescent();
let x = random(width-w);
let y = random(h, height);
text(key, x, y);
// createDiv(key + " " + counts[key]);
}
}