-
-
Save MattOates/62a5a3d4f86333939bbf to your computer and use it in GitHub Desktop.
Create a Markov parody of some input text. Makes use of KeyBag rolls.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl6 | |
use v6; | |
sub add-to-model (%model,$word,$trailing) { | |
if not %model.exists($word) { | |
%model{$word} = KeyBag.new; | |
} | |
%model{$word}{$trailing}++; | |
} | |
sub MAIN (Int :$generate = 100, Str :$start = "The") { | |
#Previous word read in | |
my $previous; | |
#Markovian bag model generated from input file Hash<Str=>KeyBag> | |
my %model := Hash.new; | |
#While we have lines read them | |
while my $line = $*IN.get { | |
#Add the words to the model | |
for $line.words -> $word { | |
if not $previous { | |
$previous = $word; | |
next; | |
} | |
add-to-model(%model,$previous,$word); | |
$previous = $word; | |
} | |
} | |
#Generate N words using the markov bag model | |
#Pick a random start word | |
my $emit = $start; | |
for ^$generate { | |
print "$emit "; | |
#Pick the next word weighted by the current word being emitted | |
$emit = %model{$emit}.roll; | |
if not $emit { | |
$emit = %model.keys.roll; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment