I have a list of several hundred members that I want to separate by First Name, Middle Name and Last name, but some of the members have prefixes (denoted by 'P'). All possible combinations:
First Middle Last
P First Middle Last
First P Middle Last
P First p Middle Last
How do I separate First (with P, if available), Middle (with P, if available) and Last names in Python? This is what I came up with but it doesn't quite work.
import csv
inPath = "input.txt"
outPath = "output.txt"
newlist = []
file = open(inPath, 'rU')
if file:
for line in file:
member = line.split()
newlist.append(member)
file.close()
else:
print "Error Opening File."
file = open(outPath, 'wb')
if file:
for i in range(len(newlist)):
print i, newlist[i][0] # Should get the First Name with Prefix
print i, newlist[i][1] # Should get the Middle Name with Prefix
print i, newlist[i][-1]
file.close()
else:
print "Error Opening File."
What I want is:
Many thanks for your help.
How about this complete test script:
import sys
def process(file):
for line in file:
arr = line.split()
if not arr:
continue
last = arr.pop()
n = len(arr)
if n == 4:
first, middle = ' '.join(arr[:2]), ' '.join(arr[2:])
elif n == 3:
if arr[0] in ('M', 'Shk', 'BS'):
first, middle = ' '.join(arr[:2]), arr[-1]
else:
first, middle = arr[0], ' '.join(arr[1:])
elif n == 2:
first, middle = arr
else:
continue
print 'First: %r' % first
print 'Middle: %r' % middle
print 'Last: %r' % last
if __name__ == '__main__':
process(sys.stdin)
If you run this on Linux, type in example lines and then press Ctrl+D to signify end-of-input. On Windows, use Ctrl+Z instead of Ctrl+D. You can also pipe in a file, of course.
The following input file:
First Middle Last
M First Middle Last
First Shk Middle Last
BS First M Middle Last
gives this output:
First: 'First'
Middle: 'Middle'
Last: 'Last'
First: 'M First'
Middle: 'Middle'
Last: 'Last'
First: 'First'
Middle: 'Shk Middle'
Last: 'Last'
First: 'BS First'
Middle: 'M Middle'
Last: 'Last'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With