Skip to content

Instantly share code, notes, and snippets.

@qlkzy
Created March 14, 2015 13:54
Show Gist options
  • Select an option

  • Save qlkzy/23b35484812653268776 to your computer and use it in GitHub Desktop.

Select an option

Save qlkzy/23b35484812653268776 to your computer and use it in GitHub Desktop.
Hacky Markov Chains over ZNC logs
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
use List::Util qw/shuffle/;
my $n = 2;
my $count = 1;
my $nickfile;
GetOptions('n=i' => \$n,
'count|c=i' => \$count,
'nickfile|k=s' => \$nickfile);
my @nickmap;
if ($nickfile) {
open (my $nh, '<', $nickfile) or die;
my $curr;
while (<$nh>) {
chomp;
next if /^\s*$/;
if (m/^\S/) {
s/\s+//g;
$curr = $_;
} else {
s/\s+//g;
push(@nickmap, [$_, $curr]);
}
}
}
my %ngrams;
while (<>) {
if (m/^[^<]*<([^>]+)>\s+(.*)$/) {
my $name = fixnick($1);
my $msg = $2;
my @words = split /\s+/, $msg;
for (0 .. $#words-$n) {
push(@{$ngrams{$name}{lc(join(' ', @words[$_ .. ($_+$n-1)]))}}, $words[$_+$n]);
}
}
}
while (my $name = prompt()) {
$name =~ s/\s//g;
next unless exists $ngrams{$name};
for (1..$count) {
my @words = split / /, (shuffle(keys %{$ngrams{$name}}))[0];
while ($#words < 16) {
my $next = (shuffle(@{$ngrams{$name}{lc(join(' ', @words[$#words-$n+1 .. $#words]))}}))[0];
if (!(defined $next)) {
last;
}
push @words, $next;
}
print "@words\n";
}
}
sub prompt {
print "> ";
return <STDIN>;
}
sub fixnick {
local $_ = shift;
s/_*$//;
for my $pat (@nickmap) {
s/.*@$pat[0].*/@$pat[1]/i;
}
return $_;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment