Home > Software design >  Construct a logical vector indicating whether a character has a middle/second name
Construct a logical vector indicating whether a character has a middle/second name

Time:06-13

['Dr. Bernard Lander', ' Donnatella Hollingdorp', ' Scott F. Fitzgerald', 'Rev. Martin Luther King', ' Theodore Snodgrass', 'Carlamina Scarfoni']

This is My List

code :

import re
middleName_list =[]
for name in names:
    
    if ("." in First):
        Middle, first = first.split(".")
            #Middle = "."
        middleName_list.append(True)
    else:
            middleName_list.append(False)

print(middleName_list)

Output i am getting :

[False, False, False, False, False, False]

Output i desired

[False, False, True, True, False, False]

CodePudding user response:

If you assume that you can identify a title as a stripped string ending with period then:

namelist = ['Dr. Bernard Lander', ' Donnatella Hollingdorp', ' Scott F. Fitzgerald', 'Rev. Martin Luther King', ' Theodore Snodgrass', 'Carlamina Scarfoni']

result = []

for name in namelist:
    tokens = name.split()
    idx = 1 if tokens[0].endswith('.') else 0
    result.append(len(tokens[idx:]) > 2)

print(result)

Output:

[False, False, True, True, False, False]

CodePudding user response:

You can use a regex for that. Assuming the titles are ending with a dot:


import re

regex = re.compile(r'(\w \.\s )?\w \s \w \.?\s \w $')

out = [bool(regex.match(n.strip())) for n in names]

Output: [False, False, True, True, False, False]

  • Related