-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpot_translations.py
87 lines (67 loc) · 2.53 KB
/
pot_translations.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# -*- coding: utf-8 -*-
import os
import pandas as pd
from mtranslate import translate
path = 'C:/Users/usuario/Desktop/Traducciones'
def process_pot(folder_path):
data_frames = []
names = []
for filename in os.listdir(folder_path):
if filename.endswith(".pot"):
filepath = os.path.join(folder_path, filename)
names.append(filename)
with open(filepath, 'r', encoding='utf-8') as file:
lines = file.readlines()
df_data = []
msgid = None
for line in lines:
if line.startswith('msgid'):
msgid = line.split('msgid')[1].strip()[1:-1]
df_data.append((msgid))
df = pd.DataFrame(df_data, columns=['msgid'])
df = df[df['msgid'] != '']
data_frames.append(df)
return data_frames, names
def translation(df):
target_lang = {'Translation_ZH': 'zh-CN'}
for column, language in target_lang.items():
translations = []
for content in df['msgid']:
try:
translation = translate(content, language, 'en')
translations.append(translation)
except Exception as e:
print(f"Error occurred during translation: {str(e)}")
translations.append(None)
df[column] = translations
df.rename(columns={column: 'msgstr'}, inplace=True)
def write_translations(filepath, translations):
with open(filepath, 'r', encoding='utf-8') as file:
lines = file.readlines()
new_lines = []
idx = 0
while idx < len(lines):
line = lines[idx]
if line.startswith('msgid'):
msgid = line.split('msgid')[1].strip()[1:-1]
msgstr = translations.get(msgid)
if msgstr is not None:
new_lines.append(line)
new_lines.append('msgstr "{}"\n'.format(msgstr))
idx += 1
else:
new_lines.append(line)
else:
new_lines.append(line)
idx += 1
with open(filepath, 'w', encoding='utf-8') as new_file:
new_file.writelines(new_lines)
results, filenames = process_pot(path)
for df in results:
translation(df)
cont = 0
for df in results:
translations = df.set_index('msgid')['msgstr'].to_dict()
filepath = 'C:/Users/usuario/Desktop/Traducciones/' + filenames[cont]
write_translations(filepath, translations)
cont += 1