xxxxxxxxxx
72
let fr = 2;
// Array of words
let words = [];
// Word count
let wc = {};
// Margin for placing text
let m = 50;
function preload() {
loadStrings('environment2.txt', count);
}
function setup() {
frameRate(fr);
createCanvas(windowWidth, windowHeight);
textAlign(CENTER, CENTER);
}
function draw() {
background('black');
for (let word in wc) {
textSize(wc[word] * 0.5);
fill('white');
text(word, random(10, width - 10), random(10, height - 10));
}
}
function count(data) {
// Go line by line
for (let d of data) {
// Turn each line into an array of words
let line = splitTokens(d);
// Add it to 1 big array
words = words.concat(line);
}
// Clean up all the words
for (let w in words) {
let word = words[w];
// Remove punctuation
word = word.replace(/[-_:;.,!?\(\)]/g,"");
// Make it all lowercase
word = word.toLowerCase();
// Get rid of whitespace around the word
word = word.trim();
// If nothing is left, get rid of it
if (word.length < 1) words.splice(w, 1);
// Otherwise put cleaned up word back in array
else words[w] = word;
}
// Index the words
for (let word of words) {
if (word in wc) wc[word]++;
else wc[word] = 1;
}
// Print word count object
console.log(wc);
// Sorted words
let sw = [];
// Create an array of objects for each word and its count
for(let word in wc) {
sw.push({word : word, count : wc[word]});
}
// Sort the array in descending order according to count
sw.sort(function(a,b) { return a.count < b.count });
console.log(sw);
}