Skip to content

Instantly share code, notes, and snippets.

@jimschubert
Created February 3, 2012 23:59
Show Gist options
  • Save jimschubert/1733871 to your computer and use it in GitHub Desktop.
Save jimschubert/1733871 to your computer and use it in GitHub Desktop.
words.pl: Find all possible slogan words from a single sentence.
#!/usr/bin/env perl
# words.pl: Find all possible slogan words from a single sentence.
use strict; $|++;
@ARGV >= 2 or die "usage: $0 input_file output_file 'sentence'\n";
my ($infile, $outfile, $sentence) = @ARGV;
$sentence = $sentence || 'how much wood could a woodchuck chuck';
open INPUT, "< $infile" or die $!;
open OUTPUT, "> $outfile" or die $!;
my $stdout = select STDOUT;
$| = 1;
select $stdout;
my %sentence_letters;
my $stmp = $sentence;
$sentence_letters{$&}++ while($stmp =~ s/[a-z]//);
print "Using the sentence '$sentence'\n";
print "Found the following letters:\n";
print "\t$_ - ". $sentence_letters{$_} ."\n" foreach(sort(keys %sentence_letters));
print "Processing $infile for slogan words\n";
my $count = 0;
my @indicators = qw{\ / | .};
LINE: while(<INPUT>) {
my $word = $_;
my $tmp = $word;
next LINE if($word =~ /['\&\d]/);
my %word_letters;
$word_letters{$&}++ while($tmp =~ s/[a-z]//);
foreach(keys %word_letters) {
next LINE if ($word_letters{$_} > $sentence_letters{$_});
}
print OUTPUT $word;
my $word_len = length($word);
open WORD_LEN_OUTPUT, ">> $outfile.$word_len";
print WORD_LEN_OUTPUT $word;
print $indicators[++$count % 4], "\r";
}
print "\nDone.\nView $outfile.* for words\n";
@jimschubert
Copy link
Author

Accompanies my blog post.

To run:

perl words.pl /usr/share/dict/words generated.txt 'Good goly, Miss Molly'

Output will resemble:

jim at schubert in ~/projects/gist-1733871 on master*
$ tree .
.
├── generated.txt
├── generated.txt.1
├── generated.txt.2
├── generated.txt.3
├── generated.txt.4
├── generated.txt.5
├── generated.txt.6
├── generated.txt.7
├── generated.txt.8
└── words.pl

0 directories, 10 files

Where generated.txt.3 should contain all 3-letter words. If the input file has \r\n instead of \n, the counts might be off by one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment