Skip to content

Instantly share code, notes, and snippets.

@dev001hajipro
Created March 26, 2017 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev001hajipro/0c21090c118bb1d863722c55ca760403 to your computer and use it in GitHub Desktop.
Save dev001hajipro/0c21090c118bb1d863722c55ca760403 to your computer and use it in GitHub Desktop.
p5.js word counter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>CodingChallenge40_WordCounter</title>
</head>
<body>
<h1>Word Counter</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.8/p5.js"></script>
<script>
let keys = []; // unique set.
let counts = [];
function getx(doRender) {
httpGet(
'http://natureofcode.com/book/chapter-3-oscillation/',
"txt",
function(resp) {
let parser = new DOMParser();
let doc = parser.parseFromString(resp, "text/html");
//document.getElementById('debugarea').innerHTML = doc.body.textContent;
// \wは英数字、\Wはそれ以外の文字列にヒット
// つまり、各種記号で分割.
let tokens = doc.body.textContent.split(/\W+/);
tokens
.map((s)=> s.toLowerCase())
.filter((v) => /^[a-z]+/.test(v))
.forEach((s)=> {
if (counts[s] === undefined) {
counts[s]=1;
keys.push(s);
} else {
counts[s]=counts[s]+1;
}
});
keys.sort((a,b)=> counts[a] - counts[b]);
// render
let fragment = document.createDocumentFragment();
for (let i = 0; i < keys.length; i++) {
let span = document.createElement('div');
const key = keys[i];
span.innerHTML = key + " " + counts[key];
fragment.appendChild(span);
}
const outputEl = document.getElementById('debugarea');
//outputEl.appendChild(fragment);
doRender && doRender(keys, counts);
},
function(err) {
console.log(err);
});
}
function setup() {
createCanvas(854, 480);
background(0);
fill(150);
getx((keys, counts)=>{
for (let i = 0; i < keys.length; i++) {
fill(color(random(255),random(255),random(255),));
textSize(map(counts[keys[i]], 1, 300, 10, 144));
text(keys[i], random(width), random(height));
}
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment