Skip to content

Instantly share code, notes, and snippets.

@ben-efiz
Last active December 10, 2015 21:18
Show Gist options
  • Save ben-efiz/4494099 to your computer and use it in GitHub Desktop.
Save ben-efiz/4494099 to your computer and use it in GitHub Desktop.
Little python script for replacing all localization with a large arrays.xml with keys and putting the string values into a new strings.xml Why doing so? See here http://developer.sinnerschrader-mobile.com/moving-localization-from-arrays-xml-to-strings-xml/463/
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description='Replacing values in arrays.xml with @string/ links. Generates two new files: <input>.new (edited arrays.xml containing the string links) and <input>.strings (resources file containing the new string keys)')
parser.add_argument('-i', '--input', help='Input file, e.g. arrays.xml', metavar='FILE', required=True)
parser.add_argument('-p', '--prefix', help='Optional prefix added to each new string key, e.g. array_')
args = vars(parser.parse_args())
xmlString = ' <string name=\"{0}\">{1}</string>'
xmlStringLink = '@string/'
xmlComment = ' <!-- {0} -->'
xmlHeader = '<?xml version=\'1.0\' encoding=\'UTF-8\'?>'
xmlResourcesBegin = '<resources>'
xmlResourcesEnd = '</resources>'
prefix = args['prefix']
if prefix is None:
prefix = ''
fi = open(args['input'])
fo = open(args['input'] + '.strings', 'w')
fa = open(args['input'] + '.new', 'w')
fo.write(xmlHeader)
fo.write('\n')
fo.write(xmlResourcesBegin)
fo.write('\n')
for l in iter(fi):
line = l.lstrip().rstrip()
if line.startswith('<string-array name=\"') and line.endswith('\">'):
fa.write(l)
# remember array name for new strings
current = line[20:-2]
fo.write(xmlComment.format(current))
fo.write('\n')
elif line.startswith('<item>') and line.endswith('</item>'):
strKey = prefix + current + '_' + line[6:-7].lower().replace(' ', '_')
strValue = line[6:-7]
# replace with string link
fa.write(l.replace(strValue, xmlStringLink + strKey))
# generate new strings
fo.write(xmlString.format(strKey, strValue))
fo.write('\n')
else:
fa.write(l)
fo.write(xmlResourcesEnd)
fi.close()
fo.close()
fa.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment