July 29, 2010

Create an offline command line dictionary using dict

Filed under: Perl — shijitht @ 9:35 pm

Most of the dictionary in our OS have online database and most of us don’t have a reliable internet connection. And the online database could be down when we need something urgent. A solution to it is to create an offline database from the online one you line. We need two things to start the process,

1) A file containing almost every English word (get online).
2) Application named dict which could be accessed from terminal as ” dict -d wn apple “.
It will show the meaning of apple from WordNet(wn) .So -d option is to select WordNet database (choose whatever meets your demand).

Now we are ready.
Connect to the net and run the following script

@words = <fr> ;
$len = @words;
for($i=0;$i<$len;$i++) {
    $word = @words[$i];
    system("dict -d wn $word > file 2>&1");
    my @file = <fp>;
    my @first = split(/ /,@file[0]);
    @first = split(//,@first[0]);
    if(@first[0] eq 'N') {
        print fw (">>".@words[$i]." - Meaning not present\n");
    } elsif(@first[0] eq 'C'){
    } else{
        $j = 4;
        print fw (">".@words[$i]."\n");
        while(@file[$j++]) {
            print fw (@file[$j]);
    undef @file;
    undef @first;

This will create a file named meanings. It carries the meaning of all words in the file words.
So file meanings is our offline database. Copy the file meanings to a directory .dictionary in home.
The next script is to get the meaning of a word from the database we just created.

#! /usr/bin/perl
$file = "$ENV{'HOME'}/.dictionary/meanings";
$tmp =  "$ENV{'HOME'}/.dictionary/tmp";
@meaning = <fr>;
$word = lc($ARGV[0]);
$a = system("grep -n -w '>$word' $file > $tmp");
if($a == 0) {
	$line = <fw>;
	@line = split(":",$line);
	$line_no = @line[0];
	while(@test[0] ne ">") {
		print @meaning[$line_no++];
		@test = @meaning[$line_no];
		@test = substr(@test[0],0,1);
} else {
	print "Not present\n";

Make the script executable and run it by giving word as argument. Copy the above script to bin and make it command.
I give it the name d and use as “d apple” to show its meaning.
You can automate the above process using Makefile.


Create a free website or blog at WordPress.com.