Ok, I have implemented a little random text/poem/haiku generator. I bumped into Julie Zelenski's webpage when I was searching for some perl poetry material. I had a look at the grammar, thought it was fun, and easy to parse. So I implemented a perl version of the grammar parser and random text/poem generator. It was pretty fun to play with, especially with a Star Trek episode generator (yeah you can tell I am a big star trek fan ;-)). Here it goes...
#!/usr/local/bin/perl -w
use strict;
use Data::Dumper;
=pod
#
# ok, the following is the location of the grammar files at
# Julie Zelenski's webpage at stanford's computer science faculty.
# I was thinking about using WWW::Mechanize or LWP::Agent to
# fetch the grammar files, but couldn't be bothered.
#
my $rsg_grammar_url
= "http://www-cs-faculty.stanford.edu/~zelenski/rsg/grammars/";
=cut
# load the grammar definition file
my $grammar = do { local $/; <DATA> };
my %grammar = %{parse_grammar($grammar)};
# print Dumper(\%grammar);
my $text = random_text_from_grammar("start");
$text =~ s/(.{50,60}(?<=\s\b))/$1\n/mg;
print "$text\n";
# parse the simple grammar and build a hash table
sub parse_grammar
{
my $grammar = shift;
my %grammar = $grammar =~ /^{\s*<([^>]+)>\s*([^}]+)}/mg;
foreach (keys %grammar) {
$grammar{$_} = [ map { s/[^\S\n]+/ /g;
s/\s([.?,;!])/$1/g;
$_ }
split /\s*;\s*/, $grammar{$_} ];
}
return \%grammar;
}
# generate the text recursively
sub random_text_from_grammar
{
my $token = shift;
my $selection = $grammar{$token};
my $phrase = $selection->[rand ($#$selection+1)];
$phrase =~ s/<([^>]+)>/random_text_from_grammar($1)/ge;
return $phrase;
}
__DATA__
When I ran it, I got some pretty interesting text -
Kyoto smile Nick through / day Kyoto drifting subway /
temple my ocean - Hokusai
rising computer / dusk Mitsukoshi day Nick / hell samurai
tree - Toshiba
wave white Tokyo wave / toward mountains higher empty /
computer faces - Hokusai
Mitsukoshi pool / sushi wave dusk Parlante / white subway
sound birds - Toshiba
Buddhist cranes cranes fly / Kyushu sun rice fields sea
through / temple white thinking - Basho
|