Friday, 13 March 2009

Python Script: Converting strings to camel case

A simple script to convert strings to camelCase


import sys

def processTokens(tokens):
result='';
for token in tokens:
if token is not None:
result=result+token.title()
return result

def processString(string,separator=' '):
li=string.split(separator)
if li is not []:
result=li[0].lower()
result=result+processTokens(li[1:])
return result

def getCamelCase(string,separator=' '):
return processString(string,separator)


if __name__=="__main__":
if sys.argv.__len__()<3:
print 'usage: camelcase [input filename] [output filename]'
else:
f=open(sys.argv[1],'r')
o=open(sys.argv[2],'w')
for line in f:
o.write(getCamelCase(line))
f.close()
o.close()

1 comments:

Mario said...

Why not just this?

def getCamelCase(s, sep=' '):
tl = []
for t in s.split(sep):
tl.append(t.title())
return ''.join(tl)

Another way, faster but less readable:

def getCamelCase(s, sep=' '):
return ''.join([t.title() for t in s.split(sep)])