快速將現(xiàn)有項目的中文字符全局替換成國際化文本
1、準(zhǔn)備一份json文本刷喜,將要修改的中文全部寫入文本荣回,如下
{
"user":"用戶",
"Home":"首頁"
}
2、準(zhǔn)備創(chuàng)建一份Python腳本
import os
import json
import re
# 函數(shù)用于替換文件中的中文文本
def replace_text_in_file(file_path, localization_dict):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 正則表達(dá)式匹配中文字符串雹锣,假設(shè)中文字符串是用單引號或雙引號包圍
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:
# 將中文文本替換為其英文鍵网沾,并在外面調(diào)用.tr方法
return f'"{key}".tr'
return match.group(0) # 如果沒找到匹配的,返回原文本
# 替換文件內(nèi)容
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文件路徑'
# 確保在運(yùn)行腳本之前已經(jīng)備份了項目
main(YOUR_FLUTTER_PROJECT_PATH, YOUR_LOCALIZATION_JSON_PATH)
print('替換完成辉哥。')