xxxxxxxxxx
81
/**
* CountingString example
* by Daniel Shiffman.
*
* Port of Processing Counting Strings example to p5.js
* http://en.wikipedia.org/wiki/Concordance_(publishing)
*
*/
// A JS object pairs Strings with integers
let concordance = {};
// The raw array of words
let lines;
let tokens;
let counter = 0;
function preload() {
lines = loadStrings("data/dracula.txt");
}
function setup() {
createCanvas(640, 360);
concordance = {};
// Load file and chop it up
let allText = join(lines, " ").toLowerCase();
tokens = allText.split(/[.?!\s]+/);
}
function draw() {
background(0);
fill(255);
// Look at words one at a time
if (counter < tokens.length) {
let s = tokens[counter];
if (!concordance[s]) {
concordance[s] = 1;
} else {
concordance[s]++;
}
counter++;
}
// x and y will be used to locate each word
let x = 0;
let y = 48;
let keys = Object.keys(concordance);
keys.sort((a, b) => concordance[a] - concordance[b]);
//console.log(keys);
// Look at each word
for (let word of keys) {
let count = concordance[word];
// Only display words that appear 3 times
if (count > 3) {
// The size is the count
let fsize = constrain(count, 0, 48);
textSize(fsize);
text(word, x, y);
// Move along the x-axis
x += textWidth(word + " ");
}
// If x gets to the end, move y
if (x > width) {
x = 0;
y += 48;
// If y gets to the end, we're done
if (y > height) {
break;
}
}
}
}