Week 2: Ceiling cat sez
February 2, 2008
This week, usng regular expressions, I continued my trouncing of the bible by taking every reference to ‘God’ and the word after it, and replacing them both with ‘Celing cat sez’. Hooray for lolcats.
Here’s the code:
// Word search and replace using regex
// Ben Leduc-Mills
// Programming A2Z, Spring 08
// Based off of code by Daniel Shiffman
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.regex.*;
public class Blm272Week2 {
public static void main (String[] args) throws IOException {
// Create an input stream and file channel
// Using first arguemnt as file name to read in
FileInputStream fis = new FileInputStream(args[0]);
FileChannel fc = fis.getChannel();
// Read the contents of a file into a ByteBuffer
ByteBuffer bb = ByteBuffer.allocate((int)fc.size());
fc.read(bb);
fc.close();
// Convert ByteBuffer to one long String
String content = new String(bb.array());
String[] words = content.split(“\\b”);
System.out.println(“Read ” + words.length + ” words from ” + args[0]);
StringBuffer reverse = new StringBuffer();
for (int i = 0; i < words.length; i++) {
String word = words[i];
reverse.append(word);
}
String result = reverse.toString();
String regex = “\\bGod\\b\\W+\\b(\\w+)\\b”; // Use any “non-word character” as a delimiter
String output = result.replaceAll(regex, “ceiling cat sez” );
System.out.println(result);
System.out.println(“running replace regex. . . “);
System.out.println(output);
// Create an output stream and file channel to write out a report
// (Also print out report to screen)
FileOutputStream fos = new FileOutputStream(args[1]);
FileChannel outfc = fos.getChannel();
// Convert content String into ByteBuffer and write out to file
bb = ByteBuffer.wrap(output.getBytes());
outfc.write(bb);
outfc.close();
//System.out.println(“Reversed text written to ” + args[1]);
}
}
Some of my favorites:
01:001:001 In the beginning ceiling cat sez the heaven and the earth.
01:001:003 And ceiling cat sez, Let there be light: and there was light.
01:001:022 And ceiling cat sez them, saying, Be fruitful, and multiply, and
fill the waters in the seas, and let fowl multiply in the
earth.
01:001:027 So ceiling cat sez man in his own image, in the image of ceiling cat sez he him; male and female created he them.
01:002:003 And ceiling cat sez the seventh day, and sanctified it: because
that in it he had rested from all his work which ceiling cat sez
and made.
01:002:007 And the LORD ceiling cat sez man of the dust of the ground, and
breathed into his nostrils the breath of life; and man became
a living soul.
01:002:008 And the LORD ceiling cat sez a garden eastward in Eden; and there
he put the man whom he had formed.
Anyway, you get the idea. Fun with lolcats.