您的当前位置:首页>全部文章>文章详情

一个利用php编写的自动翻译脚本

发表于:2024-02-03 14:28:53浏览:51次TAG: #wordpress外贸独立站 #wordpress外贸模板

介绍

一个利用php编写的自动翻译脚本

软件架构

PHP 适配PHP8,PHP7

安装教程

  1. 打开autotranslate.php 找到方法index 进行配置(1、语言包数据;2、需要翻译的语言;3、翻译键/值;4、输出格式)
  2. php autotranslate.php 运行脚本就可以获取翻译结果了

谷歌翻译对应语言代码

"sl": { "auto": "Detect language", "af": "Afrikaans", "sq": "Albanian", "am": "Amharic", "ar": "Arabic", "hy": "Armenian", "az": "Azerbaijani", "eu": "Basque", "be": "Belarusian", "bn": "Bengali", "bs": "Bosnian", "bg": "Bulgarian", "ca": "Catalan", "ceb": "Cebuano", "ny": "Chichewa", "zh-CN": "Chinese", "co": "Corsican", "hr": "Croatian", "cs": "Czech", "da": "Danish", "nl": "Dutch", "en": "English", "eo": "Esperanto", "et": "Estonian", "tl": "Filipino", "fi": "Finnish", "fr": "French", "fy": "Frisian", "gl": "Galician", "ka": "Georgian", "de": "German", "el": "Greek", "gu": "Gujarati", "ht": "Haitian Creole", "ha": "Hausa", "haw": "Hawaiian", "iw": "Hebrew", "hi": "Hindi", "hmn": "Hmong", "hu": "Hungarian", "is": "Icelandic", "ig": "Igbo", "id": "Indonesian", "ga": "Irish", "it": "Italian", "ja": "Japanese", "jw": "Javanese", "kn": "Kannada", "kk": "Kazakh", "km": "Khmer", "rw": "Kinyarwanda", "ko": "Korean", "ku": "Kurdish (Kurmanji)", "ky": "Kyrgyz", "lo": "Lao", "la": "Latin", "lv": "Latvian", "lt": "Lithuanian", "lb": "Luxembourgish", "mk": "Macedonian", "mg": "Malagasy", "ms": "Malay", "ml": "Malayalam", "mt": "Maltese", "mi": "Maori", "mr": "Marathi", "mn": "Mongolian", "my": "Myanmar (Burmese)", "ne": "Nepali", "no": "Norwegian", "or": "Odia (Oriya)", "ps": "Pashto", "fa": "Persian", "pl": "Polish", "pt": "Portuguese", "pa": "Punjabi", "ro": "Romanian", "ru": "Russian", "sm": "Samoan", "gd": "Scots Gaelic", "sr": "Serbian", "st": "Sesotho", "sn": "Shona", "sd": "Sindhi", "si": "Sinhala", "sk": "Slovak", "sl": "Slovenian", "so": "Somali", "es": "Spanish", "su": "Sundanese", "sw": "Swahili", "sv": "Swedish", "tg": "Tajik", "ta": "Tamil", "tt": "Tatar", "te": "Telugu", "th": "Thai", "tr": "Turkish", "tk": "Turkmen", "uk": "Ukrainian", "ur": "Urdu", "ug": "Uyghur", "uz": "Uzbek", "vi": "Vietnamese", "cy": "Welsh", "xh": "Xhosa", "yi": "Yiddish", "yo": "Yoruba", "zu": "Zulu" }, "tl": { "af": "Afrikaans", "sq": "Albanian", "am": "Amharic", "ar": "Arabic", "hy": "Armenian", "az": "Azerbaijani", "eu": "Basque", "be": "Belarusian", "bn": "Bengali", "bs": "Bosnian", "bg": "Bulgarian", "ca": "Catalan", "ceb": "Cebuano", "ny": "Chichewa", "zh-CN": "Chinese (Simplified)", "zh-TW": "Chinese (Traditional)", "co": "Corsican", "hr": "Croatian", "cs": "Czech", "da": "Danish", "nl": "Dutch", "en": "English", "eo": "Esperanto", "et": "Estonian", "tl": "Filipino", "fi": "Finnish", "fr": "French", "fy": "Frisian", "gl": "Galician", "ka": "Georgian", "de": "German", "el": "Greek", "gu": "Gujarati", "ht": "Haitian Creole", "ha": "Hausa", "haw": "Hawaiian", "iw": "Hebrew", "hi": "Hindi", "hmn": "Hmong", "hu": "Hungarian", "is": "Icelandic", "ig": "Igbo", "id": "Indonesian", "ga": "Irish", "it": "Italian", "ja": "Japanese", "jw": "Javanese", "kn": "Kannada", "kk": "Kazakh", "km": "Khmer", "rw": "Kinyarwanda", "ko": "Korean", "ku": "Kurdish (Kurmanji)", "ky": "Kyrgyz", "lo": "Lao", "la": "Latin", "lv": "Latvian", "lt": "Lithuanian", "lb": "Luxembourgish", "mk": "Macedonian", "mg": "Malagasy", "ms": "Malay", "ml": "Malayalam", "mt": "Maltese", "mi": "Maori", "mr": "Marathi", "mn": "Mongolian", "my": "Myanmar (Burmese)", "ne": "Nepali", "no": "Norwegian", "or": "Odia (Oriya)", "ps": "Pashto", "fa": "Persian", "pl": "Polish", "pt": "Portuguese", "pa": "Punjabi", "ro": "Romanian", "ru": "Russian", "sm": "Samoan", "gd": "Scots Gaelic", "sr": "Serbian", "st": "Sesotho", "sn": "Shona", "sd": "Sindhi", "si": "Sinhala", "sk": "Slovak", "sl": "Slovenian", "so": "Somali", "es": "Spanish", "su": "Sundanese", "sw": "Swahili", "sv": "Swedish", "tg": "Tajik", "ta": "Tamil", "tt": "Tatar", "te": "Telugu", "th": "Thai", "tr": "Turkish", "tk": "Turkmen", "uk": "Ukrainian", "ur": "Urdu", "ug": "Uyghur", "uz": "Uzbek", "vi": "Vietnamese", "cy": "Welsh", "xh": "Xhosa", "yi": "Yiddish", "yo": "Yoruba", "zu": "Zulu"

  1. xxxx
  2. xxxx
  3. xxxx
<?php
class AutoTranslate
{
    public function __construct()
    {
        /*
         *   设定百度翻译接口配置
         */
        $this->api = "http://api.fanyi.baidu.com/api/trans/vip/translate";
        $this->appid = "20180522000163934";
        $this->key = "HVhoa_DqUo78uDOB1bqZ";
        /*
        *   谷歌翻译接口配置
        */
    }
    /*
     *   入口函数
     *   需要配置的参数:
     *   1、语言包数据
     *   2、需要翻译的结果语言
     *   3、按(数组)键翻译/按(数组)值翻译
     *   4、配置语言包输出格式 (php数组,json,js数组)
     *   输出
     *   程序会按照结果语言名称在当前目录下生成对应的语言包文件 例如:zh.txt(中文语言包)
     */
    public function index()
    {
        // 1、输入语言包(json/arr)二选一,如果json有数据就用json处理
        // php数组
        $langs_arr = array(
            "现阶段公开发行尚未完成,个人交易尚未开始" => "Transfer to",
        );
        // json 输入(优先json)
        $langs_json = '';
        $tos = 'en,ukr,zh-CN,zh-TW';     //  2、需要翻译的结果语言多个语言用逗号(,)隔开
        $kv = 'k';              //  3、k:键、v:值   设置键/值来翻译(用数组的键/值作为翻译结果)
        $format = 'json';         //  4、语言包输出格式 php:php数组,js:js数组,json:json数据格式
        // 配置到此结束,下面不需要配置
        $langs = empty($langs_json) ? $langs_arr : json_decode($langs_json, true);
        // 判断输入参数是否正确
        if (!in_array($kv, array('k', 'v'))) {
            die('请设置翻译键/值参数(k/v)');
        }
        if (!in_array($format, array('php', 'json', 'js'))) {
            die('请输入正确的输出数据格式(php,json,js)');
        }
        $tos = explode(',', $tos);
        $this->tran_arr($langs, 'auto', $tos, $kv, $format);
        // echo '<pre>';
        // var_dump($langs_str);

    }
    /**
     * @description: 将字符串转换为php数组
     * @param {*} $str  输入字符串
     * @param {*} $format   输入数组格式
     * @return {*}  array   输出数组
     */
    public function str2arr($str, $format = 'auto')
    {
        // 1、识别数组类型
        // 2、
        // return $arr;
    }
    /**
     * @description: 将数组转化为翻译后的数组
     * @param {*} $langs_arr 需要翻译的语言包数组
     * @param {*} $kv   根据数组的 键/值 进行翻译
     * @param {*} $from 翻译键的语言
     * @param {*} $to   需要翻译的目标语言
     * @return {*} array 返回翻译后的数组
     */
    public function translate_arr($langs_arr, $kv = 'k', $from = 'auto', $to)
    {
        foreach ($langs_arr as $k => $v) {
            if (is_array($v)) {
                $res[$k] = $this->translate_arr($v, $kv, $from, $to); //如果是数组,调用本身方法继续翻译
            } else {
                // 显示翻译过程
                echo "正在翻译  {$$kv}=>";
                $starttime  = microtime(true);
                for ($i = 1; $i < 10; $i++) { //翻译失败20次之后停止翻译
                    $res = $this->transform($$kv, $from, $to);
                    if ($res['status'] == 1) {
                        $res[$k] = $res['data'];
                        break;
                    }
                    $res[$k] = "错误代码:{$res['status']}";
                    echo '.';
                }
                $usetime = round(microtime(true) - $starttime, 2);
                // 显示翻译过程
                echo ($res[$k] ?? "翻译失败,错误代码:{$res['status']}");
                echo "   【耗时:{$usetime}秒,请求次数:{$i} 】\n";
            }
        }
        return $res;
    }

    /**
     * @description: 将数组转换为对应语言的语言包
     * @param {*} $langarr 语言包数组,
     * @param {*} $format  需要转换的格式js/json/php
     * @return {*}
     */
    public function langarr2str($langarr, $format = 'php', $self = false, $indent = '    ')
    {
        switch ($format) {
            case 'json':
                $s1 = "";   //文件头
                $s2 = "{\n";    //数组开始
                $s3 = "\"";     //数组键符
                $s4 = ":";      //数组关系符号
                $s5 = "\"";     //数组值符号
                $s6 = ",\n";      //数组间隔符
                $s7 = "{$indent}}\n";      //数组结束符
                $s8 = "{$indent}}";   //子数组结束符
                $s9 = ",\n";   //子数组结束符
                break;
            case 'php':
                $s1 = "<?php \n return ";
                $s2 = "array(\n";
                $s3 = "\"";
                $s4 = "=>";
                $s5 = "\"";
                $s6 = ",\n";
                $s7 = "{$indent});\n";
                $s8 = "{$indent})";  //子数组结束符
                $s9 = ",\n";  //子数组结束符
                break;
            case 'js':
                $s1 = "var lang = ";
                $s2 = "{\n";
                $s3 = "";
                $s4 = ":";
                $s5 = "\"";
                $s6 = ",\n";
                $s7 = "{$indent}}\n";
                $s8 = "{$indent}}";   //子数组结束符
                $s9 = ",\n";  //子数组结束符
                break;
        }
        $langstr = $self ? '' : $s1;
        $langstr .= $s2;
        // 获取数组最后的一个键值
        $endkey = array_key_last($langarr);
        foreach ($langarr as $k => $v) {
            if (is_array($v)) {
                $v = $this->langarr2str($v, $format, true, $indent . '    ');
                $langstr .= "{$indent}{$s3}{$k}{$s3}{$s4}{$v}" . (($k == $endkey) ? "\n" : $s9);
            } else {
                $langstr .= "{$indent}{$s3}{$k}{$s3}{$s4}{$s5}{$v}{$s5}" . (($k == $endkey) ? "\n" : $s6);
            }
        }
        // 追加结尾符号
        $langstr .= $self ? $s8 : $s7;
        return $langstr;
    }

    /*
 *     输入语言
 *     参数 $langs : 需要翻译的数组
 *     参数 $from : 翻译的源语言    aoto自动检测 yue粤语 zh中文 http://api.fanyi.baidu.com/doc/21
 *     参数 $tos : 需要翻译的目标语言数组
 *     参数 $kv : 键/值作为翻译的参数
 *     参数 $format :  输出数据格式 1:json,2:php,3:js
 *     返回 string 返回翻译结果
 */
    public function tran_arr($langs_arr = array(), $from = 'auto', $tos = array(), $kv, $format = 'php')
    {
        foreach ($tos as $to) {
            // $langs_str = "<?php \n /*语言包:" . $to . "*/ \n return array( \n"; //字符串头部
            echo "\n开始翻译语言:{$to}\n";
            // 将数组翻译
            $res_arr = $this->translate_arr($langs_arr, $kv, $from, $to);
            // 将翻译完成的数组转换为对应字符串
            $res_str = $this->langarr2str($res_arr, $format);
            $file = fopen('./' . $to . ".{$format}", 'w');
            fwrite($file, mb_convert_encoding($res_str, 'UTF-8', mb_detect_encoding($res_str)));
            fclose($file);
        }
    }
    /*
 *   翻译接口
 *     参数 $q : 需要翻译的文字
 *     参数 $from : 翻译的源语言    aoto自动检测 yue粤语 zh中文 http://api.fanyi.baidu.com/doc/21
 *     参数 $to : 目标语言 yue粤语 zh中文 http://api.fanyi.baidu.com/doc/21
 *     返回 string 返回翻译结果
 */

    public function transform($q, $from, $to)
    {
        $salt = $this->GetRandStr(8);
        $api = $this->api;
        $appid = $this->appid;
        $key = $this->key;
        $data = array(
            'q' => $q,
            'from' => $from,
            'to' => $to,
            'appid' => $appid,
            'salt' => $salt,
            'sign' => md5($appid . $q . $salt . $key),
        );
        $result = $this->request('POST', $api, '0', $data);
        $data = [
            'status' => $result['error_code'] ?? 1,
            'data' => $result['trans_result'][0]['dst']
        ];
        return $data;
    }
    /*
*   腾讯翻译接口
*/
    public function translate_tencent($q, $from, $to)
    {
        $api = "https://tmt.tencentcloudapi.com/?Action=TextTranslate";
        $SecredId = 'AKIDxpSTDi5kMbbNsACZiaaLp42LNBiTZFJ6';
        $SecredKey = 'gINEpb7OP9eFcldartfhU3KL6yavzoTs';
        $header = array();
        $data = array(
            'action' => 'TextTranslate',
            'SecretId'  => $SecredId,
            'SecredKey' => $SecredKey,
            'Version' => '2018-03-21',
            'Region'    => 'ap-guangzhou',
            'SourceText'    =>  $q,
            'Source'    =>  $from,
            'Target'    =>  $to,
            'ProjectID' =>  0,
        );
    }
    /*
*   谷歌翻译接口
*/
    public function transform_google($q, $from, $to)
    {
        $api = "http://translate.google.cn/translate_a/single";
        $data = array(
            'client' => 'at',   //如果次数限制了,at 可以修改为gtx
            'sl'    => $from,   //源语言
            'tl'    => $to,    //目标语言
            'dt'    => 't',     //决定最终返回的数据结构
            'q'     => $q,
        );
        $result = $this->request('POST', $api, 0, $data);
        $data = [
            'status' => $result[0][0][0] ? 1 : 0,
            'data' => $result[0][0][0] ?? ''
        ];
        return $data;
    }
    /*
 * CURL方法
 *   method:GET/POST
 *   url:请求链接
 *   data:参数,
 *   header: 请求头
 */
    function request($method = 'GET', $url = '', $header = array(), $data = array())
    {
        $ch = curl_init(); //创建cURL资源
        // 格式化参数
        $data = http_build_query($data);
        $url = ($method == 'GET') ? ($url . '?' . $data) : $url; //设定get / post不同的url
        // 设置默认URL选项
        $defaults = array(
            CURLOPT_POST => ($method == 'POST') ? 1 : 0,
            CURLOPT_HEADER => empty($header) ? 0 : $header,
            CURLOPT_URL => $url,
            CURLOPT_FRESH_CONNECT => 1,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FORBID_REUSE => 1,
            CURLOPT_TIMEOUT => 4,
            CURLOPT_POSTFIELDS => ($method == 'POST') ? $data : 0,
        );
        $options = array();
        curl_setopt_array($ch, ($defaults + $options));
        // 抓取URL并将它传递给浏览器
        $output = curl_exec($ch);
        // 关闭cURL资源,并释放系统资源
        curl_close($ch);
        // 返回请求结果
        return json_decode($output, true);
    }
    function GetRandStr($length)
    {
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }
}
/*
 * 随机字符串生成方法
 *   参数:length:字符长度
 *   返回:string 随机字符串
 */
$login = new AutoTranslate;
$login->index();
0.094401s