Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate first, middle and last names (Python)

Tags:

python

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:

  1. Get first and middles names with their prefixes if available
  2. Output each (first, middle, last) to separate txt files, or a single CSV file (preferable).

Many thanks for your help.

like image 770
eozzy Avatar asked Jul 29 '26 02:07

eozzy


1 Answers

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'
like image 157
Vinay Sajip Avatar answered Jul 31 '26 15:07

Vinay Sajip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!