- Saved searches
- Use saved searches to filter your results more quickly
- License
- vatsel/Python-Name-Parser
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.rst
- About
- Extracting first name and last name in Python
- Extracting first name and last name in Python
- Splitting a name into first, middle and last name using Python
- Switch Lastname, Firstname to Firstname Lastname inside List
- Swapping first and last name positions
- Python program to print the initials of a name with last name in full?
- Example
- Algorithm
- Example Code
- Output
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Guess last and first names in strings. Select by popularity or maximum char usage.
License
vatsel/Python-Name-Parser
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.rst
Get last and first name information from email addresses, usernames, etc
- Built-in Dictionary of 150,000+ names and their popularity rankings.
- Distinguishes between last and first names.
- Last and First name sequence detection: Can detect invalid combinations of Last-First-Last name sequences and select the best option.
- Search by Popularity: best for mangled strings.
- Search by Longest Names: best for email addresses, or generally valid data.
- Uses Regex to extract letter sequences, breaking the input into words and considerably increasing matching probability.
- Worst case runtime of O(n**2) not counting the single regex operation above (where n = number of chars).
- Actual scan time is under a second, even for strings with hundreds of characters.
Simply call NameParser.Scan(). Input can be a string or a list of strings.
About
Guess last and first names in strings. Select by popularity or maximum char usage.
Extracting first name and last name in Python
Solution 1: use split function to make the list which has the names The first one is the first name second is your last name if names length equals to 2 Solution 2: We can use following regular expression: Which looks for a first and last name, and optionally a middle name. Here are a few intermediate versions and what they would return: Question: I need some help in writing the body for this function that swaps the positions of the last name and first name.
Extracting first name and last name in Python
I’m trying to extract all the first names AND the last names (ex: John Johnson) in a big text (about 20 pages).
I used split with \. as separator and there is my regular expression:
Unfortunately, I only get all the lines of my text instead of only the first names and last names:
Suddenly, Mary Poppins flew away with her umbrella Later in the day, John. bla bla bla
regex = re.compile("\b([A-Z][a-z]+) ([A-Z][a-z]+)\b") string = """Suddenly, Mary Poppins flew away with her umbrella Later in the day, John Johnson did something.""" regex.findall(string)
[(u'Mary', u'Poppins'), (u'John', u'Johnson')]
I’ve adapted one regular expression that can handle accents and dash for composed names:
#!/usr/bin/env python # -*- coding: utf-8 -*- import re r = re.compile('([A-Z]\w+(?=[\s\-][A-Z])(?:[\s\-][A-Z]\w+)+)', re.UNICODE) tests = < u'Jean Vincent Placé': u'Jean Vincent Placé est un excellent donneur de leçons', u'Giovanni Delle Bande Nere': u'In quest\'anno Giovanni Delle Bande Nere ha avuto tre momenti di gloria', # Here 'BDFL' may not be whished u'BDFL Guido Van Rossum': u'Nobody hacks Python like BDFL Guido Van Rossum because he created it' >for expected, s in tests.iteritems(): match = r.search(s) assert(match is not None) extracted = match.group(0) print expected print extracted assert(expected == match.group(0))
Coding bat( Python > List-1 > same_first_last, First, check whether the list is empty or not. Assuming the list is not empty. The method looks like as below. def same_first_last(nums) return True if a[0]==a[-1] else False nums[-1] is the shortcut to get the last element from a list. The nums[-n] syntax gets the nth-to-last element. Example:
Splitting a name into first, middle and last name using Python
So i am basically asking that i have a name and i need to split it into three parts and store it into three different variables using Python.
Then the desired output should be:
Additionally I want to put a check that if for some person middle name is not there then it should be blank.
use split function to make the list which has the names The first one is the first name second is your last name if names length equals to 2
names =Name.split() if len(names) ==2 : print("there is no middle name") first_name = names[0] last_name = names[1] print(f" first name - \n middle name - last name - ") elif len(names) == 3: print("there is middle name") first_name = names[0] middle_name = names[1] last_name = names[2] print(f" first name - \n middle name - \nlast name - ")
We can use following regular expression:
Which looks for a first and last name, and optionally a middle name.
import re s = "John Wayne Smith" s2 = "John Smith" p = re.compile(r"(?P\S+)\s(?:(?P\S*)\s)?(?P\S+)$")
p.match(s).groupdict() # p.match(s2).groupdict() #
Please note that match will match the entire string from start to end. Please make sure to clean and validate your inputs beforehand, as regular expressions are somewhat brittle to inputs they don’t expect.
The library nameparse is the perfect solution for your question. You can install it by
In your code, import this library as:
from nameparser import HumanName name = "John Wayne Smith" name_parts = HumanName(name) name_parts.title name_parts.first name_parts.middle name_parts.last name_parts.suffix name_parts.nickname name_parts.surnames # (middle + last) name_parts.initials # (first initial of each name part)
Python has a feature called «unpacking» which allows you to destructure objects from a list. The list in question is from calling the split method on the string. It takes a string to split with. To unpack, you must have a declaration of the form [a, b, c] = list where a, b and c are objects you wish to unpack (in order). So your code is
[first, middle, last] = 'John Wayne Smith'.split(' ')
Python — Formatting Last Name, First Name, last name, first name 45 23 34 . last name2, first name2 78 32 23 . My program is almost complete, but I need to format the ‘last name, first name’ to ‘first name, last name’ while printing the results. Here is the code of that part so you get a better idea. I’m using ‘dict()’ and .iteritems() to go through the 7 …
Switch Lastname, Firstname to Firstname Lastname inside List
I have two lists of sports players. One is structured simply:
['Lastname, Firstname', 'Lastname2, Firstname2'..]
The second is a list of lists structured:
[['Firstname Lastname', 'Team', 'Position', 'Ranking']. ]
I ultimately want to search the contents of the second list and pull the info if there is a matching name from the first list.
I need to swap ‘Lastname, Firstname’ to ‘Firstname Lastname’ to match list 2’s formatting for simplification.
Any help would be great. Thanks!
You can swap the order in the list of names with:
[" ".join(n.split(", ")[::-1]) for n in namelist]
An explanation: this is a list comprehension that does something to each item. Here are a few intermediate versions and what they would return:
namelist = ["Robinson, David", "Roberts, Tim"] # split each item into a list, around the commas: [n.split(", ") for n in namelist] # [['Robinson', 'David'], ['Roberts', 'Tim']] # reverse the split up list: [n.split(", ")[::-1] for n in namelist] # [['David', 'Robinson'], ['Tim', 'Roberts']] # join it back together with a space: [" ".join(n.split(", ")[::-1]) for n in namelist] # ['David Robinson', 'Tim Roberts']
Python — How to reverse the order of first and last name, First, define a function to reverse the name, utilizing the .split method. It takes the parameter where you want to split it at, in this case » » and returns a list of the two parts of your input string. From there we can reorganize the return string of our function how we like—in this case last name, first name.
Swapping first and last name positions
I need some help in writing the body for this function that swaps the positions of the last name and first name.
Essentially, I have to write a body to swap the first name from a string to the last name’s positions.
The initial order is first name followed by last name (separated by a comma). Example: ‘Albus Percival Wulfric Brian, Dumbledore’
The result I want is: ‘Dumbledore, Albus Percival Wulfric Brian’
But I’ve tried the following and I’m still not getting the right answer:
temp = name_list[len(name_list)-1] name_list[len(name_list)-1] = name_list[0] name_list[0] = temp
The result is a list, which is not what I want. I’m a new user to Python, so please don’t go into too complex ways of solving this.
You can do this by splitting the string by the comma—which yields a list—then reversing that list, and joining the list by a comma again to get back a string:
>>> name = 'Albus Percival Wulfric Brian, Dumbledore' >>> ', '.join(reversed(name.split(', '))) 'Dumbledore, Albus Percival Wulfric Brian'
If you can’t use the reversed function (for whatever reason), then you can do the reversal manually by storing the list elements individually first.
>>> name.split(', ') ['Albus Percival Wulfric Brian', 'Dumbledore'] >>> first, last = name.split(', ') >>> first 'Albus Percival Wulfric Brian' >>> last 'Dumbledore' >>> [last, first] ['Dumbledore', 'Albus Percival Wulfric Brian'] >>> ', '.join([last, first]) 'Dumbledore, Albus Percival Wulfric Brian' >>> last + ', ' + first 'Dumbledore, Albus Percival Wulfric Brian'
As it’s theoretically possible that the string contains multiple commas, you should consider passing 1 as the second parameter to str.split to make sure that you only perform a single split, producing two list items:
>>> 'some, name, with, way, too, many, commas'.split(', ', 1) ['some', 'name, with, way, too, many, commas']
Instead of using str.split , you can also locate the comma in the string and split up the string yourself. You can use str.find to get the index of the comma, and then use sequence splicing to split up the string:
>>> name.index(',') 28 >>> name[:28] # string up to index 28 'Albus Percival Wulfric Brian' >>> name[30:] # string starting at index 30 (we have to consider the space too) 'Dumbledore' >>> index = name.index(',') >>> name[index + 2:] + ', ' + name[:index] 'Dumbledore, Albus Percival Wulfric Brian'
You don’t need many built in functions for this
return name[name.find(',')+2:]+", "+name[:name.find(',')]
Extracting first names from list of full names in Python, 5 Answers. lst = [‘michelle rodriguez’, ‘dexter king’, ‘gurukavari’] print ( [x.split () [0] for x in lst]) # [‘michelle’, ‘dexter’, ‘gurukavari’] Would advise to use Map function, and to split each of the iterable items by space character, and return only the first of the split items. Use a split function to separate the first name & last …
Python program to print the initials of a name with last name in full?
Here we use different python inbuilt function. First we use split().split the words into a list. Then traverse till the second last word and upper() function is used for print first character in capital and then add the last word which is title of a name and here we use title(),title function converts the first alphabet to capital.
Example
Input Pradip Chandra Sarkar Output P.C Sarkar
Algorithm
fullname(str1) /* str1 is a string */ Step 1: first we split the string into a list. Step 2: newspace is initialized by a space(“”) Step 3: then traverse the list till the second last word. Step 4: then adds the capital first character using the upper function. Step 5: then get the last item of the list.
Example Code
# python program to print initials of a name def fullname(str1): # split the string into a list lst = str1.split() newspace = "" # traverse in the list for i in range(len(lst)-1): str1 = lst[i] # adds the capital first character newspace += (str1[0].upper()+'.') # l[-1] gives last item of list l. newspace += lst[-1].title() return newspace # Driver code str1=input("Enter Full Name ::>") print("Short Form of Name Is ::>",fullname(str1))
Output
Enter Full Name ::>pradip chandra sarkar Short Form of Name Is ::> P.C.Sarkar
I love programming (: That’s all I know