vue快速实现国际化 - py代码批量替换文件内指定字符(根据国际化配置)

需求: vue快速实现国际化文案key替换

py代码快速批量用国际化key值替换文件内指定文案value值

  • 国际化cn配置
export default {
  save: '保存',
  cacel: '取消',
  ...
}

  • 国际化en配置
export default {
  save: 'Save',
  cacel: 'Cacel',
  ...
}

py代码

from multiprocessing import context
import os
import json
import re
from readline import insert_text

def replace_swich_file(file_path, input_json,pattern):
    """
    在指定的文本文件中,根据提供的替换字典进行替换操作。

    参数:
    - file_path: 要进行替换的文本文件路径
    - input_json: 包含替换字典的 JSON 格式的字符串
    """
    try:
        if file_path.endswith(('.js')):
            replace_file_js(file_path, input_json,pattern)
        if file_path.endswith(('.vue')):
            replace_file_vue(file_path, input_json,pattern)

    except FileNotFoundError:
        print(f"找不到文件: {file_path}")
    except json.JSONDecodeError as e:
        print(f"JSON 解析错误: {e}")

def find_file(directory_path,input_json,pattern):
    for filename in os.listdir(directory_path):
        file_path = os.path.join(directory_path, filename)
        if os.path.isfile(file_path):
            # ------------- 跳过路径 -------------------
            if 'BasicData' in file_path:
                continue
            if 'i18n' in file_path:
                continue
            # ------------- 拦截文件 -------------------
            if file_path.endswith(('.js','.vue')):
                replace_swich_file(file_path,input_json,pattern)
        else:
           find_file(file_path,input_json,pattern)

# JS文件格式
def replace_file_js(file_path, input_json,pattern):
    return
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # 逐行替换,跳过注释 // 或 <!-- 的行
    # 跨行
    skip_commom = False;
    for i, line in enumerate(lines):
        if "//" in lines[i]:
            continue
        if "<!--" in lines[i]:
            skip_commom = True;
            if "-->" in lines[i]:
                skip_commom = False;
            continue
        if "-->" in lines[i]:
            skip_commom = False;
        if skip_commom:
            continue
        match = pattern.search(lines[i])
        if match and match is not None and match != '':
            key = match.group(0)[1:-1]
            if not key:
                continue
            # 替换代码 js 语法
            key_val = input_json.get(key)
            if key_val is None:
                continue
            replace_match = "i18n.t('"+key_val+"')"
            lines[i] = pattern.sub(replace_match, lines[i])

    with open(file_path, 'w', encoding='utf-8') as file:
        file.writelines(lines)

# vue文件格式
def replace_file_vue(file_path, input_json,pattern):
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    in_srcipt = False;
    # 逐行替换,跳过注释 // 或 <!-- 的行
    # 跨行
    skip_commom = False
    for i, line in enumerate(lines):
        if "//" in lines[i]:
            continue
        if "<!--" in lines[i]:
            skip_commom = True;
            if "-->" in lines[i]:
                skip_commom = False;
            continue
        if "-->" in lines[i]:
            skip_commom = False;
        if skip_commom:
            continue
        if '<script>' in lines[i]:
            in_srcipt = True
        if '</script>' in lines[i]:
            in_srcipt = False
        match = pattern.search(lines[i])
        if match and match is not None and match != '':
            key = match.group(0)[1:-1]
            if not key:
                continue
            key_val = input_json.get(key)
            if key_val is None:
                continue
            # 替换代码 js 语法
            if in_srcipt:
                continue
                replace_match = "this.$t('" + key_val + "')"
                lines[i] = pattern.sub(replace_match, lines[i])
            # 替换代码 标签 语法
            else:
                #标签内
                #    <xx>
                #       中文
                #    <xx>
                newline = line.strip().replace('\\n','').replace('\\t','')
                print("---"+newline+"---")
                if len(newline) < 10:
                    print(newline+"---"+key)
                    replace_match = "{{$t('" + key_val + "')}}"
                    lines[i] = pattern.sub(replace_match, lines[i])
                #标签中的元素
                else:
                    continue
                    replace_match = "$t('" + key_val + "')"
                    lines[i] = pattern.sub(replace_match, lines[i])

    with open(file_path, 'w', encoding='utf-8') as file:
        file.writelines(lines)

if __name__ == '__main__':
    file_path = "/Users/chenchong/py_project/soft.json"
    # 指定代码路径
    target_directory = []
    target_directory.append("/Users/chenchong/IdeaProjects/gwm-swip/iov-foundation-web")
    with open(file_path, 'r', encoding='utf-8') as file:
        input_json = json.loads(file.read())
        #生成正则表达式模式,以匹配所有要替换的字符串
        pattern = re.compile('|'.join(re.escape("\""+key+"\"")+
                            '|'+re.escape(key)+
                            '|'+re.escape("\""+key+"\":")+
                            '|'+re.escape("\""+key+"\":")+
                            '|'+re.escape("\'"+key+"\'")+
                            '|'+re.escape("\'"+key+"\':")+
                            '|'+re.escape("\'"+key+"\':")
                            for key in input_json.keys()))
    # 提取中文并打印
    for dir in target_directory:
        find_file(dir,input_json,pattern)


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容