Skip to content

Instantly share code, notes, and snippets.

@admackin
Last active September 4, 2015 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save admackin/330983 to your computer and use it in GitHub Desktop.
Save admackin/330983 to your computer and use it in GitHub Desktop.
Convert from underscores to camel case, if you randomly change conventions
# converts the input string with underscores from eg lower_camel_case to lowerCamelCase (do you like what I did with the name there?)
# should work reasonably on anything with vaguely C-like syntax (not LISP probably, but who really cares?)
from contextlib import nested
def camelCaseWord(underscored):
output_vals = []
prev_idx = 0
und_idx = underscored.find('_')
while und_idx != -1:
output_vals.append(underscored[prev_idx:und_idx])
output_vals.append(underscored[und_idx+1:und_idx+2].upper())
prev_idx = und_idx + 2
und_idx = underscored.find('_', prev_idx)
output_vals.append(underscored[prev_idx:])
return ''.join(output_vals)
def camelCaseNonCaps(underscored):
if any(c.islower() for c in underscored):
return camelCaseWord(underscored)
else:
return underscored
def camelCaseLine(line):
return re.sub(r"(\w+)", lambda m: camelCaseNonCaps(m.group()), line)
def camelCaseFile(input, output):
with nested(open(input) as inf, open(output, 'w') as outf):
for line in inf:
outf.write(camelCaseLine(line))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment