某在线翻译脚本,参数是gbk编码的字符串……
用在某在线翻译程序里,每次调一次这个脚本……
带了一个简单的缓存,用BDB缓存已经翻译过的东西。
Google Translate API要钱而且很贵,所以后来改Bing了……
#!/usr/bin/perl
use DB_File;
use URI::Escape;
$filename = '/home/henryhu/.tranlate_cache.db';
$res = `echo -n '$ARGV[0]' | iconv -f gbk`;
$query = $res;
#print $query;
$query = uri_escape($query);
#print $query;
tie %cache, 'DB_File', $filename, O_CREAT|O_RDWR , 0777, $DB_HASH;
if ($cache{$query})
{
$tag = "F";
$result = $cache{$query};
} else {
$tag = "N";
$url = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=<Bing API key>&text=$query&from=ja&to=zh-CN";
# $url = "https://www.googleapis.com/language/translate/v2?key=<Google API key>&q=$query&source=ja&target=zh-CN";
$res2 = `curl -s '$url'`;
# print $res2;
foreach ($res2)
{
# if (/"translatedText":\s*"(.*)"/)
if (/<string[^>]*>(.*)/)
{
$result = $1;
}
}
$cache{$query} = $result;
}
$omit = 0;
if ($cache{"last"})
{
if ($cache{"last"} eq $query)
{
$omit = 1;
}
}
if (not $omit)
{
print "$tag $result\n";
}
$cache{"last"} = $query;
untie %cache;