/* Daniel Shiffman */ /* Programming from A to Z */ /* Concordance in Processing */ /* Spring 2008 */ package concordance.processing; import java.io.*; import java.util.*; import a2z.*; import java.util.regex.*; import concordance.treemap.Word; import processing.core.PApplet; import processing.core.PFont; public class ConcordanceProcessing2 extends PApplet { TreeMap words; PFont f; Iterator iterator; boolean iteratorSet; int width = 900; int height = 600; public void setup() { size(width, height); frameRate(20); fillConcordance("obama.txt"); f = createFont("Arial",16,true); iteratorSet = false; } public void draw() { background(255); // We're done, print out contents of Tree! if (iteratorSet == false) { System.out.println("Here are the contents of your tree:"); iterator = words.values().iterator(); iteratorSet = true; } if (iterator.hasNext()) { Word word = (Word) iterator.next(); System.out.println(word.getWord() + " " + word.getCount()); textAlign(CENTER); fill(255- word.getCount()*50, 0, 0); textFont(f,word.getCount()*50); text(word.getWord(), width/2, height/2 + word.getCount()*10); } else { iterator = words.values().iterator(); } // noLoop(); } public void fillConcordance(String path) { try { A2ZFileReader fr = new A2ZFileReader(path); String content = fr.getContent(); // Step 2, create an empty Tree words = new TreeMap(); // Step 3, break input file up into words // We are doing this with split and a regular expression String regex = "\\b"; String tokens[] = content.split(regex); // We'll use a regular exrpession to match words with only // characters and apostrophes // Throwing away all the punctuation (we could do this with a // different split regex too) Pattern p = Pattern.compile("[a-z']+",Pattern.CASE_INSENSITIVE); // For every word for (int i = 0; i < tokens.length; i++) { String s = tokens[i].toLowerCase(); // If it matches our regex, insert it in the tree Matcher m = p.matcher(s); if (m.matches()) { if (words.containsKey(s)) { Word w = (Word) words.get(s); w.count(); } else { Word w = new Word(s); words.put(s,w); } } } } catch (IOException e) { System.out.println("File I/O Error"); e.printStackTrace(); } } }