Flutter 全局替换成国际化文本格式
2024-03-06 本文已影响0人
木马不在转
快速将现有项目的中文字符全局替换成国际化文本
1、准备一份json文本,将要修改的中文全部写入文本,如下
{
"user":"用户",
"Home":"首页"
}
2、准备创建一份Python脚本
import os
import json
import re
# 函数用于替换文件中的中文文本
def replace_text_in_file(file_path, localization_dict):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 正则表达式匹配中文字符串,假设中文字符串是用单引号或双引号包围
chinese_pattern = re.compile(r"(['\"])([\u4e00-\u9fff]+)\1")
def replacement(match):
chinese_text = match.group(2)
for key, value in localization_dict.items():
if value == chinese_text:
# 将中文文本替换为其英文键,并在外面调用.tr方法
return f'"{key}".tr'
return match.group(0) # 如果没找到匹配的,返回原文本
# 替换文件内容
content = chinese_pattern.sub(replacement, content)
# 写回文件
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
# 加载国际化JSON文件
def load_localization(filepath):
with open(filepath, 'r', encoding='utf-8') as file:
return json.load(file)
# 遍历指定目录下所有.dart文件,并替换其中的中文文本
def main(project_path, localization_file_path):
localization_dict = load_localization(localization_file_path)
for root, dirs, files in os.walk(project_path):
for file in files:
if file.endswith('.dart'):
replace_text_in_file(os.path.join(root, file), localization_dict)
if __name__ == '__main__':
# 配置你的Flutter项目路径和国际化JSON文件路径
YOUR_FLUTTER_PROJECT_PATH = '项目文件路径'
YOUR_LOCALIZATION_JSON_PATH = 'json文件路径'
# 确保在运行脚本之前已经备份了项目
main(YOUR_FLUTTER_PROJECT_PATH, YOUR_LOCALIZATION_JSON_PATH)
print('替换完成。')