From 48ecda2123572b352b3c713dc04ae83a5edfbb3a Mon Sep 17 00:00:00 2001 From: Gorayan Date: Wed, 18 Aug 2021 06:45:24 +0900 Subject: [PATCH] =?UTF-8?q?=E3=82=AF=E3=82=A9=E3=83=BC=E3=83=86=E3=83=BC?= =?UTF-8?q?=E3=82=B7=E3=83=A7=E3=83=B3=E3=81=A7=E5=9B=B2=E3=81=BE=E3=82=8C?= =?UTF-8?q?=E3=81=A6=E3=81=84=E3=82=8B=E6=96=87=E5=AD=97=E5=88=97=E3=81=A0?= =?UTF-8?q?=E3=81=91=E7=BF=BB=E8=A8=B3=E3=81=99=E3=82=8B=E3=82=88=E3=81=86?= =?UTF-8?q?=E3=81=AB=E3=81=97=E3=81=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 25 +++++++++++++++++++------ requirements.txt | 2 +- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/main.py b/main.py index d55d7f6..0bb6185 100644 --- a/main.py +++ b/main.py @@ -1,11 +1,19 @@ import os +import re + from google.cloud import translate_v2 as translate -import yaml +from ruamel import yaml +from ruamel.yaml.comments import CommentedMap, CommentedSeq +from ruamel.yaml.scalarstring import DoubleQuotedScalarString import sys # Google Cloud Translation API で翻訳 def transtate(text): + + if not isinstance(text, DoubleQuotedScalarString): + return text + result = client.translate(text, target_language='ja') text = result["translatedText"] text = text.translate(str.maketrans({chr(0xFF01 + i): chr(0x21 + i) for i in range(94)})) @@ -16,11 +24,11 @@ def transtate(text): # 再起処理で子要素を翻訳していく def recursive_transtate(yaml_element): - if isinstance(yaml_element, list): + if isinstance(yaml_element, CommentedSeq): return list(map(recursive_transtate, yaml_element)) - elif isinstance(yaml_element, dict): + elif isinstance(yaml_element, CommentedMap): for key in yaml_element.keys(): @@ -51,17 +59,22 @@ def recursive_transtate(yaml_element): # pathからyamlファイルを読み込む with open(target_file_path, 'r', encoding="utf-8") as yml: - loaded_yaml = yaml.safe_load(yml) + loaded_yaml = yaml.round_trip_load(yml, preserve_quotes=True) # 翻訳 recursive_transtate(loaded_yaml) target_file_path = os.path.splitext(target_file_path)[0] -output_path = target_file_path + "_translated.yml" +target_file_name = os.path.split(target_file_path)[1] + +if dest_path == "": + output_path = target_file_path + "_translated.yml" +else: + output_path = os.path.dirname(dest_path) + "/" + target_file_name + "_translated.yml" if os.path.exists(output_path): os.remove(output_path) # output_pathにカキコ with open(output_path, 'w', encoding="utf-8") as file: - yaml.dump(loaded_yaml, file, allow_unicode=True) + yaml.round_trip_dump(loaded_yaml, stream=file, allow_unicode=True) diff --git a/requirements.txt b/requirements.txt index 3f37d64..cbd8447 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ -pyyaml~=5.4.1 +ruamel.yaml==0.17.10 google-cloud-translate==2.0.1 \ No newline at end of file