-
Notifications
You must be signed in to change notification settings - Fork 1
/
txt2xml.py
80 lines (64 loc) · 2.38 KB
/
txt2xml.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
#!/usr/bin/python2.7
#
# txt2xml.py
#
# Author: Sam Lin
# Created: July 8, 2015
import sys
import os
import re
import codecs
import shutil
import collections
from xml.dom.minidom import Document
XML_FILE_NAME = "strings.xml"
XML_FILE_DIR_PREFIX = "values-"
class unicodetxt_to_android_stringxml_obj:
def __init__(self):
if len(sys.argv) != 2:
print 'usage: ./txt2xml.py file'
sys.exit(1)
self.txtfd = 0
self.xmlfd = 0
self.langls = []
self.stringdict = collections.OrderedDict()
def parse_txt_file(self, txt_fname):
cwd = os.path.dirname(sys.argv[0])
self.txt_fd = codecs.open(os.path.join(cwd,txt_fname),'r','utf-16')
ls = [line.strip().encode('utf-8') for line in self.txt_fd]
self.txt_fd.close()
self.langls = ls[0].split('\t')
for i in ls[1:]:
subls = i.split('\t')
self.stringdict[subls[0]] = subls[1:]
def build_xml_file(self):
cwd = os.path.dirname(sys.argv[0])
lsdir = os.listdir('.')
# Remove directories whose name are start with "values-".
for i in lsdir:
if i.startswith(XML_FILE_DIR_PREFIX):
shutil.rmtree(i)
for j in self.langls:
# Create the directories according to the language.
os.mkdir(XML_FILE_DIR_PREFIX + j)
doc = Document()
resources = doc.createElement("resources")
doc.appendChild(resources)
for k,v in self.stringdict.items():
stringele = doc.createElement("string")
stringele.setAttribute("name",k)
text = doc.createTextNode(v[self.langls.index(j)])
stringele.appendChild(text)
resources.appendChild(stringele)
# The hacky solution see:
# http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python
uglyXml = doc.toprettyxml(indent=' ')
text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
prettyXml = text_re.sub('>\g<1></', uglyXml)
self.xmlfd = open(os.path.join(XML_FILE_DIR_PREFIX + j,XML_FILE_NAME),'w')
#doc.writexml(self.xmlfd)
self.xmlfd.write(prettyXml)
self.xmlfd.close()
obj = unicodetxt_to_android_stringxml_obj()
obj.parse_txt_file(sys.argv[1])
obj.build_xml_file()