【问题标题】:How to write Python wrapper around perl program?如何围绕 perl 程序编写 Python 包装器?
【发布时间】:2014-02-11 07:04:08
【问题描述】:

我在这里发布一个 perl 程序,以使用 perl 程序查找两个同义词集之间的相似性:

#! /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__

在终端上我将其用作:

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$

谁能告诉我如何为这个 perl 程序编写一个 python 包装器?

【问题讨论】:

标签: python perl wrapper integrate


【解决方案1】:

你可以使用 subprocess 模块从 python 调用 perl 脚本,管道它的标准输出然后分析它:

#!/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

【讨论】:

  • 非常感谢安德烈·索博列夫。对我很有帮助
【解决方案2】:

我可以看到以下几个选项:

  1. 您可以按照 andrey 的建议使用 subprocess,并解析 perl 程序的输出。缺点是耗时 - 每次调用都会启动一个新进程。
  2. 您可以使用 pyperl 将 perl 函数调用集成到您的 python 脚本中。
  3. 或者 - 你可以将你的 perl 代码翻译成 python。从长远来看,这可能是最好的方法,这样就不必维护一个 python/perl 混合环境。你可以使用一个 Wordnet 的 python 包装器。

所以,这实际上取决于您的需求。最快最简单的方法当然是第一种。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-30
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多