Question

Here I am posting a perl program to find similarity between two synsets using perl program:

#! /usr/bin/perl -w 
use strict;
use warnings;
use WordNet::QueryData;
use WordNet::Similarity::random;
use WordNet::Similarity::lesk;
use WordNet::Similarity::vector; 
use WordNet::Similarity::vector_pairs; 

# Get the concepts.
my $wps1 = shift;
my $wps2 = shift;

unless (defined $wps1 and defined $wps2) {
    print STDERR "Undefined input\n";
    print STDERR "Usage: sample.pl synset1 synset2\n";
    print STDERR "\tSynsets must be in word#pos#sense format (ex., dog#n#1)\n";
    exit 1;
}

print STDERR "Loading WordNet... ";
my $wn = WordNet::QueryData->new;
die "Unable to create WordNet object.\n" if(!$wn);
print STDERR "done.\n";

# Create an object for each of the measures of semantic relatedness.

print STDERR "Creating lesk object... ";
my $lesk = WordNet::Similarity::lesk->new($wn, "config-files/config-lesk.conf");
die "Unable to create lesk object.\n" if(!defined $lesk);
my ($error, $errString) = $lesk->getError();
die $errString if($error > 1);
print STDERR "done.\n";

# Find the relatedness of the concepts using each of the measures.

my $value = $lesk->getRelatedness($wps1, $wps2);
($error, $errString) = $lesk->getError();
die $errString if($error > 1);

print "LESK Similarity = $value\n";
print "LESK ErrorString = $errString\n" if $error;
__END__

and on terminal I am using it as:

coep@coep:~/WordNet-Similarity-2.05/samples$ perl sample.pl church#n#1 temple#n#1
Loading WordNet... done.
Creating lesk object... done.
LESK Similarity = 77
coep@coep:~/WordNet-Similarity-2.05/samples$

Can anyone tell me how to write a python wrapper for this perl program?

Was it helpful?

Solution

Yo can invoke perl script from python using subprocess module, piping its stdout and then analyzing it:

#!/usr/bin/env python

import subprocess

set1 = 'church#n#1'
set2 = 'temple#n#1'
cmd = ['perl', './sample.pl', set1, set2]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in proc.stdout:
    if 'Similarity' in line:
        similarity = int(line.split("=")[-1])
print similarity

OTHER TIPS

Here are a couple of options I can see:

  1. you could use subprocess as andrey suggested, and parse the output of the perl program. The downside is time consumption - starting a new process every call.
  2. You could use pyperl to integrate a perl function call into your python script.
  3. OR - you could translate your perl code to python. This is probably the best way in the long run so as not having to maintain a python/perl mixed up environment. there is a Wordnet wrapper for python you could use.

So, it depends on your needs really. The quickest and easiest way would be the first of course.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top