import json
import requests
以下に設定をして使用します
# 変換前言語
LANG_FROM = "ja";
# 変換後言語
LANG_TO = "it"
# 変換ファイル(".arbの場所")
FILE_PATH = "/content/drive/MyDrive/XXXXX";
FILE_PATH_FROM = FILE_PATH + LANG_FROM + ".arb";
FILE_PATH_TO = FILE_PATH + LANG_TO + ".arb";
# DeepL設定
DEEPL_API_KEY = "XXXXX"
DEEPL_URL = "https://api-free.deepl.com/v2/translate";
from google.colab import drive
drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
list = []
def load_json(file_name):
with open(file_name, 'r', encoding="utf8") as f:
data = json.loads(f.read())
for key in data:
value = data[key]
if isinstance(value, dict):
fromJson(key, value)
else:
list.append({
"key": key,
"value": value.replace("\n", "<0\>")
})
def write_json(file_name, data):
with open(file_name, 'w', encoding="utf8") as f:
f.write(json.dumps(data, ensure_ascii=False, indent=4))
def toJson(list):
json = {}
for entry in list:
value = entry["value"].replace("<0\>", "\n")
key = entry["key"]
split = key.split(".")
json_builder = json
for i in range(0, len(split) - 1):
if not split[i] in json_builder:
json_builder[split[i]] = {}
json_builder = json_builder[split[i]]
json_builder[split[len(split) - 1]] = value
return json
def fromJson(path, json_file):
for key in json_file:
value = json_file[key]
if isinstance(value, dict):
fromJson(path + "." + key, value)
else:
list.append({
"key": path + "." + key,
"value": value.replace("\n", "<0\>")
})
def tranlate_deepl_free(value, from_language, to_language):
if value is None:
return None
if value == "":
return ""
if from_language == to_language:
return value
else:
params = {
"auth_key": DEEPL_API_KEY,
"text": value,
"source_lang": from_language,
"target_lang": to_language
}
response = requests.post(DEEPL_URL, data=params)
if response.status_code == 200:
return response.json()["translations"][0]["text"]
else:
print("Error: " + str(response.status_code))
print(response.text)
return value
print("ファイル読み込み開始")
load_json(FILE_PATH_FROM)
print("翻訳開始")
for key in list:
key["value"] = tranlate_deepl_free(key["value"], LANG_FROM, LANG_TO)
print("ファイル書き込み開始")
write_json(FILE_PATH_TO, toJson(list))
print("処理終了")
ファイル読み込み開始 翻訳開始 ファイル書き込み開始 処理終了