|
| 1 | +#!/usr/bin/env jruby -w |
| 2 | +require 'picrate' |
| 3 | +# A helper to keep track of word frequency. |
| 4 | +class Word |
| 5 | + attr_accessor :word |
| 6 | + attr_reader :count |
| 7 | + def initialize(word) |
| 8 | + @word = word |
| 9 | + @count = 1 |
| 10 | + end |
| 11 | + |
| 12 | + def increment |
| 13 | + @count += 1 |
| 14 | + end |
| 15 | +end |
| 16 | + |
| 17 | +################################ |
| 18 | +# This sketch is translated from a vanilla processing sketch by Daniel Schiffman |
| 19 | +# that was designed to demonstrate the use IntHash class in vanilla processing. |
| 20 | +# Similar results can easily be obtained using more idiomatic ruby. Here IntHash |
| 21 | +# has been replaced by a String => Word hash (as used in a Schiffman prototype). |
| 22 | +# Read about concordance here:- |
| 23 | +# http://en.wikipedia.org/wiki/Concordance_(publishing) |
| 24 | +################################ |
| 25 | +class CountingWords < Processing::App |
| 26 | + attr_reader :concordance, :lines, :tokens, :counter |
| 27 | + |
| 28 | + def setup |
| 29 | + sketch_title 'Counting words' |
| 30 | + @counter = 0 |
| 31 | + @concordance = {} |
| 32 | + # Open a file, read its contents, and 'scan' for words using a regex. |
| 33 | + # Include words with apostrophe eg Harker's |
| 34 | + @tokens = File.read(data_path('dracula.txt')).scan(/[\w'-]+/) |
| 35 | + text_font(create_font('Georgia', 24)) |
| 36 | + end |
| 37 | + |
| 38 | + def draw |
| 39 | + background 51 |
| 40 | + fill 255 |
| 41 | + s = tokens[counter] == 'I' ? tokens[counter] : tokens[counter].downcase |
| 42 | + @counter = (counter + 1) % tokens.length |
| 43 | + if concordance.key? s |
| 44 | + # Get the word object and increase the count |
| 45 | + # We access objects from a Hash via its key, the String |
| 46 | + concordance[s].increment # increment word count |
| 47 | + else |
| 48 | + # Otherwise make a new Word instance and add it to |
| 49 | + # the Hash using the word String as the key |
| 50 | + concordance[s] = Word.new(s) |
| 51 | + end |
| 52 | + # x and y will be used to locate each word |
| 53 | + x = 0 |
| 54 | + y = height - 10 |
| 55 | + # Look at each word |
| 56 | + concordance.values.each do |w| |
| 57 | + # Only display words that appear 3 times |
| 58 | + if w.count > 3 # access word count |
| 59 | + # The size is the count |
| 60 | + fsize = constrain(w.count, 0, 100) |
| 61 | + text_size(fsize) |
| 62 | + text(w.word, x, y) |
| 63 | + # Move along the x-axis |
| 64 | + x += text_width(w.word) + 1 |
| 65 | + end |
| 66 | + # If x gets to the end, move y |
| 67 | + # If y == 0 we are done |
| 68 | + no_loop if y.zero? |
| 69 | + next unless x >= width |
| 70 | + x = 0 |
| 71 | + y = y < 0 ? 0 : y - 100 |
| 72 | + end |
| 73 | + end |
| 74 | + |
| 75 | + def settings |
| 76 | + size 640, 360 |
| 77 | + end |
| 78 | +end |
| 79 | + |
| 80 | +CountingWords.new |
0 commit comments