项目都做完了,领导要求国际化????--JAVA后端篇

avatar
作者
猴君
阅读量:0

springboot项目国际化相信各位小伙伴都会,很简单,但是怎么项目都做完了,领导却要求国际化文件就很头疼了

国际化的SpringBoot代码:

第一步:创建工具类

/**  * 获取i18n资源文件  *  * @author bims  */ public class MessageUtils {     /**      * 根据消息键和参数 获取消息 委托给spring messageSource      *      * @param code 消息键      * @param args 参数      * @return 获取国际化翻译值      */     public static String message(String code, Object... args)     {         MessageSource messageSource = SpringUtils.getBean(MessageSource.class);         return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());     }      public static String message(String code, Locale locale, Object... args)     {         try{             //SpringUtils             MessageSource messageSource = SpringUtils.getBean(MessageSource.class);             if(locale==null){                 locale=LocaleContextHolder.getLocale();             }             return messageSource.getMessage(code, args,locale );         }catch (Exception e){             return code;         }     } } 

对于Bean的处理在SpringUtils中是这样的:

    /**      * 获取类型为requiredType的对象      *      * @param clz      * @return      * @throws org.springframework.beans.BeansException      *      */     public static <T> T getBean(Class<T> clz) throws BeansException     {         T result = (T) beanFactory.getBean(clz);         return result;     } 

第二步:配置yml 

# Spring配置 spring:   # 资源信息   messages:     # 国际化资源文件路径     basename: static/i18n/message,static/i18n/store,static/i18n/menu

第三步:创建Python扫描工程--尽力了啊,有些实在匹配不上规则,大佬的话可以自己研究

import os import re  # 遍历目录及其子目录下的所有.java文件 def scan_java_files(root_dir):     java_files = []     for root, _, files in os.walk(root_dir):         for file in files:             if file.endswith('.java'):                 java_files.append(os.path.join(root, file))     return java_files   # 判断是否为注释行 def is_comment_line(line):     # 抓取每行的关键词,碰到返回的就翻译,这样拼装格式的可能不会翻译,自己研究吧     return ((line.count("AjaxResult.")>0 or line.count("ajaxResult.")>0 or             line.strip().startswith("throw new")) and not line.count(".format") >0 and not line.count('getErrorUS')>0)   def extract_outer_parentheses_parts(input_string):     arrs = input_string.split("+");     res = []     for arr in arrs:         if arr.strip().startswith('"') and arr.strip().endswith('"'):             pass         else:             res.append(arr)     return res  # 扫描并翻译Java工程中的中文字符 def translate_java_project(root_dir):     java_files = scan_java_files(root_dir)     translated_texts = {}     translated_china_texts = {}     leng = 0     for java_file in java_files:         # 去掉domian数据         if java_file.count("domain") > 0:             continue         with open(java_file, 'r', encoding='utf-8') as file:             content_lines = file.readlines()         flag = 0         flag2 = 0         for line in content_lines:             pattern = re.compile(r'[\u4e00-\u9fff]')             # 查找字符串中是否有中文字符             match = re.search(pattern, line)             if is_comment_line(line) and match:                 flag2 = 1             if "com.xxx.common.utils.MessageUtils" in line:                 flag = 1         # 更新Java文件中的中文字符为国际化键         with open(java_file, 'w', encoding='utf-8') as file:             for line in content_lines:                 if flag == 0 and flag2 == 1 and "package" in line:                     line += '\n' + "import com.xxx.common.utils.MessageUtils;"                 if is_comment_line(line):                     pattern = re.compile(r'[\u4e00-\u9fff]')                     # 查找字符串中是否有中文字符                     match = re.search(pattern, line)                     if match:                         arrs = get_params(line)                         n = len(arrs)                         for i in range(n):                             chinese_chars = re.findall(r'([\u4e00-\u9fa5]+)', arrs[i])                             if len(chinese_chars) > 0:                                 chinese_str = ''.join(chinese_chars)                                 chinese_text = convert_string(arrs[i])                                 if chinese_str not in translated_china_texts:                                     translated_china_texts[chinese_str] = chinese_text                                 str = 'MessageUtils.message("' + chinese_str + '"'                                 params = extract_outer_parentheses_parts(arrs[i])                                 if len(params) > 0:                                     for param in params:                                         str += ("," + param)                                 str += ")"                                 arrs[i] = str                                 flag2 = 1                         print(arrs)                         print("变更前:" + line)                         match = re.search(r'\((.*)\)', line)                         if match:                             content_inside_brackets = match.group(1)                             line = line.replace(content_inside_brackets, ",".join(arrs))                             print("变更后:" + line)                 file.write(line)     # 写入i18n文件     with open('messages.text', 'w', encoding='utf-8') as i18n_file:         for chinese_text, translated_text in translated_china_texts.items():             i18n_file.write(f'{chinese_text}={translated_text}\n')      with open('messages_zh_cn.text', 'w', encoding='utf-8') as i18n_file:         for chinese_text, translated_text in translated_china_texts.items():             i18n_file.write(f'{chinese_text}={translated_text}\n')      with open('messages_en_us.text', 'w', encoding='utf-8') as i18n_file:         for chinese_text, translated_text in translated_texts.items():             i18n_file.write(f'{chinese_text}=\n')   def get_params(method_string):     match = re.search(r'\((.*)\)', method_string)     if match:         content_inside_brackets = match.group(1)         arr = content_inside_brackets.split(",")         indices = [i for i, item in enumerate(arr) if item.count('"') % 2 != 0]         arr2 = [indices[i:i + 2] for i in range(0, len(indices), 2)]         for start, end in arr2:             corrected_str = ','.join(arr[start:end + 1])             arr[start:end + 1] = [corrected_str] * (end + 1 - start)         arr = [x for i, x in enumerate(arr) if x not in arr[:i]]         return arr     else:         return [] def convert_string(input_string):     arrs = input_string.split("+");     input_string = ""     index = 0     for arr in arrs:         print(arr)         if arr.strip().startswith('"') and arr.strip().endswith('"'):             input_string += arr.replace('"', '')         else:             input_string+='{'+(str(index))+"}"             index += 1     return input_string  def get_line(line,translated_china_texts,flag2):     arrs = get_params(line)     n = len(arrs)     for i in range(n):         chinese_chars = re.findall(r'([\u4e00-\u9fa5]+)', arrs[i])         if len(chinese_chars) > 0:             chinese_str = ''.join(chinese_chars)             chinese_text = convert_string(arrs[i])             if chinese_str not in translated_china_texts:                 translated_china_texts[chinese_str] = chinese_text             str = 'MessageUtils.message("' + chinese_str + '"'             params = extract_outer_parentheses_parts(arrs[i])             if len(params) > 0:                 for param in params:                     str += ("," + param)             str += ")"             arrs[i] = str             flag2 = 1     print(arrs)     print("变更前:" + line)     match = re.search(r'\((.*)\)', line)     if match:         content_inside_brackets = match.group(1)         line = line.replace(content_inside_brackets,",".join(arrs))         print("变更后:" + line) if __name__ == '__main__':     translate_java_project('G:\\xxx\\xxx')     # input_string = 'e.getA(sds)+"案件,比,萨饼"+e.getA(sds)+e.getB(asa)+e.getC(asd)'     # print(convert_string('"运行时异常:" + serviceException.getServiceMsg()'))     # print(extract_outer_parentheses_parts('500,"运行时异常:" + serviceException.getServiceMsg()'))     # print(get_params('  throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));'))     # print(get_line('                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));',{},flag2=0))     # print(has_unmatched_parentheses("wesf()csd"))     # get_test('throw new ServiceException("500", "未获取到字段缓存数据");')

    关注公众号:资小库,问题快速答疑解惑

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!