|
| 1 | +/** |
| 2 | + * CountingString example |
| 3 | + * by Daniel Shiffman. |
| 4 | + * |
| 5 | + * This example demonstrates how to use a StringHash to store |
| 6 | + * a number associated with a String. Java HashMaps can also |
| 7 | + * be used for this, however, this example uses the simple StringHash |
| 8 | + * class offered by Processing's data package. |
| 9 | + |
| 10 | + */ |
| 11 | + |
| 12 | +// The next line is needed if running in JavaScript Mode with Processing.js |
| 13 | +/* @pjs font="Georgia.ttf"; */ |
| 14 | + |
| 15 | +IntHash concordance; // HashMap object |
| 16 | +String[] tokens; |
| 17 | +int counter = 0; |
| 18 | + |
| 19 | +void setup() { |
| 20 | + size(640, 360); |
| 21 | + |
| 22 | + concordance = new IntHash(); |
| 23 | + |
| 24 | + // Load file and chop it up |
| 25 | + String[] lines = loadStrings("dracula.txt"); |
| 26 | + String allText = join(lines, " "); |
| 27 | + tokens = splitTokens(allText, " ,.?!:;[]-"); |
| 28 | + |
| 29 | + // Create the font |
| 30 | + textFont(createFont("Georgia", 24)); |
| 31 | +} |
| 32 | + |
| 33 | +void draw() { |
| 34 | + background(51); |
| 35 | + fill(255); |
| 36 | + |
| 37 | + // Look at words one at a time |
| 38 | + String s = tokens[counter]; |
| 39 | + counter = (counter + 1) % tokens.length; |
| 40 | + concordance.increment(s); |
| 41 | + |
| 42 | + // x and y will be used to locate each word |
| 43 | + float x = 0; |
| 44 | + float y = 100; |
| 45 | + |
| 46 | + concordance.sortValues(); |
| 47 | + |
| 48 | + String[] keys = concordance.keyArray(); |
| 49 | + |
| 50 | + // Look at each word |
| 51 | + for (String word : keys) { |
| 52 | + int count = concordance.get(word); |
| 53 | + |
| 54 | + // Only display words that appear 3 times |
| 55 | + if (count > 3) { |
| 56 | + // The size is the count |
| 57 | + int fsize = constrain(count, 0, 100); |
| 58 | + textSize(fsize); |
| 59 | + text(word, x, y); |
| 60 | + // Move along the x-axis |
| 61 | + x += textWidth(word + " "); |
| 62 | + } |
| 63 | + |
| 64 | + // If x gets to the end, move y |
| 65 | + if (x > width) { |
| 66 | + x = 0; |
| 67 | + y += 100; |
| 68 | + // If y gets to the end, we're done |
| 69 | + if (y > height) { |
| 70 | + break; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
0 commit comments