Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Random word generator

by rooneyl (Sexton)
on Feb 27, 2008 at 14:14 UTC ( #670637=perlquestion: print w/replies, xml ) Need Help??
rooneyl has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, I need to generate a random word. I have bodged it by generating random characters, and passing this to the Aspell dictionary. Unfortunately this makes a list of words of all lengths, where I need to generate a word of a certain length. Could someone advise me on how to modify this to show only words of a certain length, or is there another way. I'm using the current version of Aspell (with test::apsell) and perl 5.8.8 on solaris. Thank you in advance for any help.

Replies are listed 'Best First'.
Re: Random word generator
by McDarren (Abbot) on Feb 27, 2008 at 14:29 UTC
    I'm not familiar with solaris, but as it's a *nix system I'd imagine you'll find a wordlist in somewhere like /usr/dict/words.

    Using this as a base, it's fairly trivial to generate random words. You can restrict the length with the built in length function.

    Alternatively, there is always CPAN - Data::Random::WordList, for example. You could use that to generate the words, and again use length to throw away the ones that are not the right length.

    Update: And for no other reason than I felt like it ;), here is a short snippet of code that demonstrates how one might do this (in this case, using shuffle() from List::Util):

    #!/usr/bin/perl -l use strict; use warnings; use List::Util qw/shuffle/; my $wordlist = '/usr/share/dict/words'; my $length = 10; my $numwords = 10; my @words; open WORDS, '<', $wordlist or die "Cannot open $wordlist:$!"; while (my $word = <WORDS>) { chomp($word); push @words, $word if (length($word) == $length); } close WORDS; my @shuffled_words = shuffle(@words); print for @shuffled_words[0 .. 9];

    Hope this helps,
    Darren :)

      Thank you for your help. Much appreciated. I like the List::Util version, the Data:Random:wordlist isn't that good at returning words of a given length. I needed to get a large list to ensure a number of words of the length required.
Re: Random word generator
by kyle (Abbot) on Feb 27, 2008 at 15:57 UTC

    As others have suggested, if you want a dictionary word, you need a dictionary. The solutions I've seen so far, however, have involved loading the whole dictionary into memory to select your word. I think you could do this without loading the whole dictionary, however. See How do I pick a random line from a file? for the basic algorithm, which could be adapted to apply only to words of a certain length.

    Update: I just couldn't resist writing it myself.

    use strict; use warnings; my $desired_length = 8; my $selected_word; my $candidate_count = 0; open my $dict_fh, '<', '/usr/share/dict/words' or die "Can't read '/usr/share/dict/words': $!\n"; WORD: while ( my $word = <$dict_fh> ) { chomp $word; next WORD if length $word != $desired_length; $selected_word = $word if rand ++$candidate_count < 1; } print "Selected '$selected_word' out of $candidate_count candidates.\n +";
      my @word_list; sub rand_word { my $file = shift; if ( not defined $word_list[0] ){ open FIN, "<$file" or die("$file"); @word_list = map { chomp; $_ } <FIN>; close FIN; } my $r = int(rand(@word_list)); return $word_list[$r]; }
Re: Random word generator
by moklevat (Priest) on Feb 27, 2008 at 14:32 UTC
    It would be much easier to help improve your code if you posted what you have already tried. However, if I understand the problem correctly, I suggest the following:

  • Get a dictionary file and extract all words of length N.
  • Read the list of all N-character words into an array.
  • Select a random element from the array.
Re: Random word generator
by erik (Sexton) on Feb 27, 2008 at 15:37 UTC
    I can see that ASPELL's dictionaries are there : I guess you could put all of the 5-letters-long words in 1 file (1 word on each line). Let's call it "wordbase.txt". Then all you have to do is :
    # make the wordbase into an array open(FH, "wordbase.txt"); my @words = <FH>; close FH; # select the word randomly in the wordbase my $random_index = int(rand($#words)); my $random_word = $words[$random_index]; print "$random_word\n";
Re: Random word generator
by Your Mother (Chancellor) on Feb 27, 2008 at 23:21 UTC

    Just because, not because you should.

    perl -nle 'BEGIN{$l=shift} END{print $line} length == $l && $lc++ || next ; rand($lc) < 1 && ($line = $_)' 4 /usr/share/dict/words

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://670637]
Approved by McDarren
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2017-11-23 18:29 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (337 votes). Check out past polls.