python - 如何编写 Perl 程序的 Python 包装器?

标签 python perl wrapper integrate

这里我发布了一个 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 包装器?

最佳答案

Yo 可以使用 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

关于python - 如何编写 Perl 程序的 Python 包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21695293/

相关文章:

regex - 如何在 Perl 正则表达式中允许文字点?

regex - 使用 Perl 计算字符串中的连续字符数

c# - 使用 C++ 包装器时如何访问 C# .dll 属性

python - 给定一个方法名作为字符串,如何获取方法实例?

python - 我不能递减 N,但我可以在评估逻辑时使用它。有人可以解释一下吗?

python - 如何展平 Pandas 数据框

python - 升级 Ipython 时出现问题(prompt_toolkit 不兼容)

perl - 有没有带调试功能的免费 Windows Perl IDE?

用于 Google map API 支持的 .NET 库

Python (Pandas) 计算百分比变化