-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
63 lines (51 loc) · 1.89 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import sys
import glob
import json
from pathlib import Path
from google_trans_new import google_translator
import re
import threading
import multiprocessing
translator = google_translator()
def startTranslate(srcFolder, desFolder, srcLang, desLang):
Path(desFolder).mkdir(parents=True, exist_ok=True)
files = []
for file in glob.glob(srcFolder+"/*.arb"):
files.append(file)
threads = []
for file in files:
threads.append(multiprocessing.Process(
target=_translateFile, args=(file, desFolder, srcLang, desLang)))
for thread in threads:
thread.start()
def _translateFile(file, desFolder, srcLang, desLang):
with open(file, encoding="utf8") as json_file:
data = json.load(json_file)
for key, value in data.items():
if key.find('@') == -1:
data[key] = _translateAndProcess(
data[key], srcLang, desLang)
print(data[key])
with open(desFolder+'/'+file[file.rindex('\\')+1:], 'w+', encoding='utf8') as outfile:
json.dump(data, outfile, ensure_ascii=False, indent=4,)
def _translateAndProcess(text, srcLang, desLang):
translatedText = translator.translate(
text, lang_src=srcLang, lang_tgt=desLang).strip()
if translatedText.find('{') == -1:
return translatedText
else:
pattern = re.compile(r'{(.+?)}')
srcVars = re.findall(pattern, text)
desVars = re.findall(pattern, translatedText)
for i in range(len(srcVars)):
translatedText = translatedText.replace(desVars[i], srcVars[i])
return translatedText
if __name__ == "__main__":
if len(sys.argv) == 5:
srcFolder = sys.argv[1]
desFolder = sys.argv[2]
srcLang = sys.argv[3]
desLang = sys.argv[4]
startTranslate(srcFolder, desFolder, srcLang, desLang)
else:
print("Invalid argument")