-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringsFileUtil.py
executable file
·81 lines (63 loc) · 2.16 KB
/
StringsFileUtil.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
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
from Log import Log
import codecs
import re
import io
def removeComments(s):
for x in re.findall(r'("[^\n]*"(?!\\))|(//[^\n]*$|/(?!\\)\*[\s\S]*?\*(?!\\)/)', s, 8):
s = s.replace(x[1], '')
return s
class StringsFileUtil:
'iOS Localizable.strings file util'
@staticmethod
def writeToFile(keys, values, directory, name, additional):
if not os.path.exists(directory):
os.makedirs(directory)
Log.info("Creating iOS file:" + directory + name)
fo = open(directory + "/" + name, "wb")
for x in range(len(keys)):
if values[x] is None or values[x] == '':
Log.error("Key:" + keys[x] +
"\'s value is None. Index:" + str(x + 1))
continue
key = str(keys[x]).strip()
value = str(values[x])
content = "\"" + key + "\" " + "= " + "\"" + value + "\";\n"
fo.write(content.encode())
if additional is not None:
fo.write(additional)
fo.close()
@staticmethod
def getKeysAndValues(path):
if path is None:
Log.error('file path is None')
return
# 1.Read localizable.strings
encodings = ['utf-8', 'utf-16']
for e in encodings:
try:
file = codecs.open(path, 'r', encoding=e)
string = file.read()
file.close()
except UnicodeDecodeError:
print('got unicode error with %s , trying different encoding' % e)
else:
break
# 2.Remove comments
string = removeComments(string)
# 3.Split by ";
localStringList = string.split('\";')
list = [x.split(' = ') for x in localStringList]
# 4.Get keys & values
keys = []
values = []
for x in range(len(list)):
keyValue = list[x]
if len(keyValue) > 1:
key = keyValue[0].split('\"')[1]
value = keyValue[1][1:]
keys.append(key)
values.append(value)
return (keys, values)