Skip to content

Instantly share code, notes, and snippets.

@ktraff
Created August 16, 2014 15:19
Show Gist options
  • Save ktraff/7609e9e277cbb8c48bd6 to your computer and use it in GitHub Desktop.
Save ktraff/7609e9e277cbb8c48bd6 to your computer and use it in GitHub Desktop.
import csv
import re
f = open('out.csv','w')
def title_case(s, exceptions=['a', 'an', 'of', 'the', 'is']):
word_list = re.split(' ', s) #re.split behaves as expected
final = [word_list[0].capitalize()]
for word in word_list[1:]:
final.append(word in exceptions and word or word.capitalize())
return " ".join(final)
def parseFirstName(f_name, name, email):
""" Attempts to find the first name from full name and email and defaults to something reasonable if not successful. """
if f_name:
# Remove everything but the first name.
return title_case(f_name.split(' ', 1)[0])
elif name:
# Return everything except the last name.
tokens = name.split(' ')
f_name_tokens = tokens[:-1]
if f_name_tokens and f_name_tokens[-1] not in ['&', 'and']:
# Avoid the case "John & Jane"
return title_case(" ".join(f_name_tokens))
else:
return title_case(" ".join(tokens))
return "Reader"
with open('in.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
f.write(",".join(reader.next()) + '\n')
for idx, row in enumerate(reader):
email = row[0]
f_name = row[1]
l_name = row[2]
name = row[3]
first_name = parseFirstName(f_name, name, email)
f.write(",".join([email, first_name, l_name, name] + row[4:]) + '\n')
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment