-
Notifications
You must be signed in to change notification settings - Fork 34
/
poetry_from_poetry_with_variations.pl
executable file
·91 lines (68 loc) · 1.7 KB
/
poetry_from_poetry_with_variations.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/perl
# Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 09 February 2017
# https://github.com/trizen
# An experimental poetry generator, using a given poetry as input,
# replacing words with random words from groups of alike ending words.
# usage:
# perl poetry_from_poetry.pl [poetry.txt] [wordlists]
use 5.016;
use strict;
use autodie;
use warnings;
use open IO => ':utf8', ':std';
use File::Find qw(find);
my $poetry_file = shift(@ARGV);
@ARGV
|| die "usage: $0 [poetry.txt] [wordlists]\n";
my $poetry = do {
open my $fh, '<', $poetry_file;
local $/;
<$fh>;
};
my $ending_len = 3; # word ending length
my $group_len = 0; # the number of words in a group - 1
my $word_regex = qr/[\pL]+(?:-[\pL]+)?/;
my %words;
my %seen;
sub collect_words {
my ($file) = @_;
open my $fh, '<', $file;
my $content = do {
local $/;
<$fh>;
};
close $fh;
while ($content =~ /($word_regex(?:\h+$word_regex){$group_len})/go) {
my $word = CORE::fc($1);
my $len = $ending_len;
if (length($word) > $len) {
next if $seen{$word}++;
push @{$words{substr($word, -$len)}}, $word;
}
}
}
find {
no_chdir => 1,
wanted => sub {
if ((-f $_) and (-T _)) {
collect_words($_);
}
},
} => @ARGV;
my @keys = keys(%words);
my %endings;
$poetry =~ s{($word_regex)}{
my $word = $1;
my $len = $ending_len;
if (length($word) <= $len) {
$word;
}
else {
my $ending = CORE::fc(substr($word, -$len));
my $key = ($endings{$ending} //= $keys[rand @keys]);
exists($words{$key}) ? $words{$key}[rand @{$words{$key}}] : $word;
}
}ge;
say $poetry;