BrainsOfSteel
BrainsOfSteel

Reputation: 107

How to generate a list of suggestions for given word in Perl?

I have created a custom dictionary which contains a list of words. Now the plan is to create a program in Perl which takes a word and generate a list of words (say 5 of them) which are closest (lexical order) to that given word from that dictionary. Now I would like to know if there is a module already available which helps me do that. If not, then how do i go about achieving such thing? Thanks in advance

Upvotes: 1

Views: 102

Answers (2)

Schwern
Schwern

Reputation: 164699

Yes, Search::Dict will efficiently find the word, or the closest word, in a dictionary file. This program will find the words around the entered word.

#!/usr/bin/perl
use strict;
use warnings;
use autodie;
use v5.10;

use Search::Dict;
use POSIX qw(ceil floor);

my $target = shift;
my $Window_Size = 5;
my @window;

open my $fh, "/usr/share/dict/words";

# Find the spot in the file where the word
# is >= our word.
# Use dictinoary order and ignore case.
my $pos = look $fh, $target, 1, 1;

# Add the next words
for(1..ceil($Window_Size/2)) {
    my $word = <$fh>;
    chomp $word;

    redo if $word eq $target;

    push @window, $word;
}

# Read the previous block of words
my $string;
seek $fh, $pos - 256, 0;
read $fh, $string, 256;
my @previous_words = split /\n/, $string;

# Add them to our list at the front.
for(1..floor($Window_Size/2)) {
    unshift @window, pop @previous_words;
}

say join ", ", @window;

For example...

$ perl ~/tmp/test.plx foot
fooster, foosterer, footage, footback, football

Edge cases like what if your word is "A" or "Zyzzogeton" are left as an exercise.

Upvotes: 1

Chankey Pathak
Chankey Pathak

Reputation: 21666

I guess you are working on auto correction feature. I worked on a similar feature and Text::SpellChecker really helped me a lot. This module uses aspell or hunspell in the background so multilingual support is also there. It checks words with spelling mistake and provides suggestions for the same.

use Text::SpellChecker;
($Text::SpellChecker::pre_hl_word,
 $Text::SpellChecker::post_hl_word) = (qw([ ]));

my $checker = Text::SpellChecker->new(text => "Foor score and seven yeers ago");

while (my $word = $checker->next_word) {
    print $checker->highlighted_text, 
        "\n", 
        "$word : ",
        (join "\t", @{$checker->suggestions}),
        "\nChoose a new word : ";
    chomp (my $new_word = <STDIN>);
    $checker->replace(new_word => $new_word) if $new_word;
}

Hope this helps.

Upvotes: 2

Related Questions