i18n国际化快速开发

描述:i18n配置一个比对替换太麻烦了,为简化效率,解放双手,有了如下开发流程。

开发流程#

  1. 使用vue-i18n-generator快速生成占位符和中文配置文件(详见说明文档)。
    vue-i18n-generatorhttps://gitee.com/thesadboy/vue-i18n-generator
    注意:使用自定义key,这样可以减少重复value。
  2. 1步骤后生成配置文件zh_cn.js将其调整为json方便后端获取。
  3. 编写Java脚本自动翻译和替换自定义key为英文,翻译采用有道SDK,详见:https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html
    代码实现:
public class VueI18nGenerator {
    private static final String APP_KEY = "";     // 有道翻译应用ID
    private static final String APP_SECRET = "";  // 有道翻译应用密钥

    public static void main(String[] args) throws Exception {
        //需要遍历的项目src路径
        String targetPath = "D:\\vue-project\\src";
        //1步骤生成的配置文件路径
        String cnJsonPath ="D:\\vue-project\\zh_cn.json";
        //获取配置文件Json
        String cnJsonContent = new String(Files.readAllBytes(Paths.get(cnJsonPath)), StandardCharsets.UTF_8);
        JSONObject jsonObject = JSONUtil.parseObj(cnJsonContent);
        //新中英文配置Json
        JSONObject chineseJson = new JSONObject();
        JSONObject englishJson = new JSONObject();
        //遍历配置文件,翻译value为英文
        jsonObject.keySet().forEach(key -> {
            String chinese = (String)jsonObject.get(key);
            String english = translate(chinese, "zh-CHS", "en", "computers");
            System.out.println("翻译文本:" + chinese + " -> " + english);
            chineseJson.set(english, chinese);
            englishJson.set(english, english);
            try {
                //遍历文件替换key为翻译的英文值(使用英文占位符避免代码维护困难)
                Files.walk(Paths.get(targetPath))
                        .filter(path -> path.toString().endsWith(".vue") || path.toString().endsWith(".js"))
                        .forEach(path -> {
                            try {
                                String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
                                String replaceStr = fileContent.replaceAll("'" + key + "'", "'" + english + "'");
                                Files.write(path, replaceStr.getBytes(StandardCharsets.UTF_8));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
            }catch (Exception e){
                e.printStackTrace();
            }

        });
        System.out.println("中文配置:" + chineseJson);
        System.out.println("英文配置:" + chineseJson);
        // 写入新的i18n中英文配置文件
        try {
            Path cnTargetPath = Paths.get("D:\\vue-project\\lang\\zh_cn.json");
            if (!Files.exists(cnTargetPath )) {
                Files.createFile(cnTargetPath );
            }
            Files.write(cnTargetPath , chineseJson.toString().getBytes(StandardCharsets.UTF_8));
            Path enTartgetPath = Paths.get("D:\\vue-project\\lang\\zh_en.json");
            if (!Files.exists(enTartgetPath)) {
                Files.createFile(enTartgetPath);
            }
            Files.write(enTartgetPath, englishJson.toString().getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String translate(String q, String from, String to, String domain) {
        // 添加请求参数
        Map<String, String[]> params = createCn2EnRequestParams(q, from, to, domain);
        // 添加鉴权相关参数
        try {
            AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
            //休眠2秒后再调用,防止调用频率过高
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // 请求api服务
            byte[] result = HttpUtil.doPost("https://openapi.youdao.com/api", null, params, "application/json");
            // 打印返回结果
            if (result != null) {
                String resultStr = new String(result, StandardCharsets.UTF_8);
                JSONObject jsonObject = JSONUtil.parseObj(resultStr);
                String errorCode = jsonObject.get("errorCode").toString();
                if(ObjectUtil.equals("0", errorCode)){
                    JSONArray translationArray =  jsonObject.getJSONArray("translation");
                    return (String)translationArray.get(0);
                }else{
                    System.out.println("翻译异常,errorCode:" + errorCode);
                    translate(q, from, to, domain);
                }
            }
        } catch (NoSuchAlgorithmException e) {
            System.out.println("翻译异常,正在重试!");
            translate(q, from, to, domain);
        }
        return "翻译异常,请重试!";
    }

    private static Map<String, String[]> createCn2EnRequestParams(String q, String from, String to, String domain) {
        /*
         * note: 将下列变量替换为需要请求的参数
         * 取值参考文档: https://ai.youdao.com/DOCSIRMA/html/%E8%87%AA%E7%84%B6%E8%AF%AD%E8%A8%80%E7%BF%BB%E8%AF%91/API%E6%96%87%E6%A1%A3/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1/%E6%96%87%E6%9C%AC%E7%BF%BB%E8%AF%91%E6%9C%8D%E5%8A%A1-API%E6%96%87%E6%A1%A3.html
         */
        return new HashMap<String, String[]>() {{
            put("q", new String[]{q});
            put("from", new String[]{from});
            put("to", new String[]{to});
            put("domain", new String[]{domain});
        }};
    }

}
  1. 生成新的中英文配置文件zh_cn.jsonzh_en.json后调整为js文件,设置为对应的i18n配置即可。

注意事项#

  1. vue-i18n-generator能帮你完成90%+的操作,可能会存在一部分中文未替换,记得核对下所有功能避免缺漏。
  2. 有翻译要求的需要核对下翻译。
  3. vue-i18n-generator可能造成部分语法错误,需手动处理,一般不多。
posted @   IamHzc  阅读(5)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩