Skip to content

Instantly share code, notes, and snippets.

@hibiyasleep
Last active February 1, 2018 03:11
Show Gist options
  • Save hibiyasleep/541eff2b92db9e7976f46d97924fd8d3 to your computer and use it in GitHub Desktop.
Save hibiyasleep/541eff2b92db9e7976f46d97924fd8d3 to your computer and use it in GitHub Desktop.
Celeste langfile parser (to translator-friendly CSV format)
#!/usr/bin/env python2
import sys
import csv
import re
_in = sys.argv[1] # input .txt
try:
_out = sys.argv[2] # output .csv
except IndexError:
_out = 'output.csv'
if not _in:
raise IOError, 'No input file specified'
keys = []
result = {}
mode = None
lastkey = None
regex_comment = re.compile('^\t*(#.*)')
regex_key = re.compile('^\t(?P<key>[A-Za-z0-9_]+)=[\t ]*(?P<value>.*)$')
regex_indented = re.compile('^\t\t(.+)')
with open(_in, 'r') as f:
content = f.readlines()
for line in content:
if lastkey:
if line.isspace() or regex_indented.match(line):
result[lastkey] += line.strip() + '\n'
continue
else:
result[lastkey] = result[lastkey].rstrip()
lastkey = None
comment_match = regex_comment.match(line)
key_match = regex_key.match(line)
if comment_match:
keys.append(line.strip())
elif key_match:
groups = key_match.groupdict()
key = groups['key']
value = groups['value']
keys.append(key)
if value == '':
lastkey = key
result[key] = ''
else:
result[key] = value
with open(_out, 'w+') as f:
writer = csv.writer(f)
for i in keys:
if i[0] == '#':
writer.writerow([i])
else:
writer.writerow([i, result.get(i)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment