-
Notifications
You must be signed in to change notification settings - Fork 33
/
poetry_from_poetry.pl
executable file
·87 lines (67 loc) · 1.56 KB
/
poetry_from_poetry.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
#!/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 other similar 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 $starting_len = 2; # word starting length
my $ending_len = 2; # word ending length
my %words;
my %seen;
sub generate_key {
my ($word) = @_;
substr($word, 0, $starting_len) . substr($word, -$ending_len);
}
sub collect_words {
my ($file) = @_;
open my $fh, '<', $file;
my $content = do {
local $/;
<$fh>;
};
close $fh;
while ($content =~ /([\pL]+)/g) {
my $word = CORE::fc($1);
if (length($word) > $ending_len) {
next if $seen{$word}++;
my $key = generate_key($word);
push @{$words{$key}}, $word;
}
}
}
find {
no_chdir => 1,
wanted => sub {
if ((-f $_) and (-T _)) {
collect_words($_);
}
},
} => @ARGV;
$poetry =~ s{([\pL]+)}{
my $word = $1;
if (length($word) <= $ending_len) {
$word;
}
else {
my $key = generate_key($word);
exists($words{$key}) ? $words{$key}[rand @{$words{$key}}] : $word;
}
}ge;
say $poetry;