Random sentence from book: Difference between revisions
Content added Content deleted
m (minor cleanup) |
No edit summary |
||
Line 431: | Line 431: | ||
</pre> |
</pre> |
||
=={{header|Perl}}== |
|||
<lang perl>#!/usr/bin/perl |
|||
use strict; # https://rosettacode.org/wiki/Random_sentence_from_book |
|||
use warnings; |
|||
my $book = do { local (@ARGV, $/) = 'waroftheworlds.txt'; <> }; |
|||
my (%one, %two); |
|||
s/^.*?START OF THIS\N*\n//s, s/END OF THIS.*//s, |
|||
tr/a-zA-Z.!?/ /c, tr/ / /s for $book; |
|||
my $qr = qr/(\b\w+\b|[.!?])/; |
|||
$one{$1}{$2}++, $two{$1}{$2}{$3}++ while $book =~ /$qr(?= *$qr *$qr)/g; |
|||
sub weightedpick |
|||
{ |
|||
my $href = shift; |
|||
my @weightedpick = map { ($_) x $href->{$_} } keys %$href; |
|||
$weightedpick[rand @weightedpick]; |
|||
} |
|||
sub sentence |
|||
{ |
|||
my @sentence = qw( . ! ? )[rand 3]; |
|||
push @sentence, weightedpick( $one{ $sentence[0] } ); |
|||
push @sentence, weightedpick( $two{ $sentence[-2] }{ $sentence[-1] } ) |
|||
while $sentence[-1] =~ /\w/; |
|||
shift @sentence; |
|||
"@sentence\n\n" =~ s/\w\K (?=[st]\b)/'/gr =~ s/ (?=[.!?]\n)//r |
|||
=~ s/.{60,}?\K /\n/gr; |
|||
} |
|||
print sentence() for 1 .. 10;</lang> |
|||
{{out}} |
|||
<pre> |
|||
The Kingston and Richmond defences forced! |
|||
I heard a scream under the seat upon which their systems were |
|||
unprepared slain as the impact of trucks the sharp whistle of |
|||
the lane my brother for the clinking of the dying man in a flash |
|||
of lightning saw between my feet to the post office a little |
|||
note in the City with the last man left alive. |
|||
I said and a remote weird crying. |
|||
said the woman over the bridges in its arrival. |
|||
In a few paces stagger and go with him all that it was to be |
|||
answered faintly. |
|||
Quite enough said the lieutenant. |
|||
I assented. |
|||
Eh? |
|||
The houses seemed deserted. |
|||
</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |