Extracting name as first name last name in python

可紊 提交于 2019-12-11 15:15:13

问题


I have a text file with lines as:

Acosta, Christina, M.D. is a heart doctor

Alissa Russo, M.D. is a heart doctor

is there a way to convert below line:

Acosta, Christina, M.D. is a heart doctor

to

Christina Acosta, M.D. is a heart doctor

Expected Output:

Christina Acosta, M.D. is a heart doctor
Alissa Russo, M.D. is a heart doctor

回答1:


You can use the follow regex to group the first and last names and substitute them in reverse order without the comma:

import re
data = '''Acosta, Christina, M.D. is a heart doctor
Alissa Russo, M.D. is a heart doctor'''
print(re.sub(r"([a-z'-]+), ([a-z'-]+)(?=,\s*M.D.)", r'\2 \1', data, flags=re.IGNORECASE))

This outputs:

Christina Acosta, M.D. is a heart doctor
Alissa Russo, M.D. is a heart doctor



回答2:


testline = 'Acosta, Christina, M.D. is a heart doctor'
a = testline.split(',', 1)
b = a[1].split(',',1)
newstring = b[0]+' '+a[0]+','+ b[1]
print newstring

your output should be: Christina Acosta, M.D. is a heart doctor




回答3:


Try this

import re
pattern = "(\w+), (\w+), M.D. is a heart doctor"
my_string = "Acosta, Christina, M.D. is a heart doctor"
re.sub(pattern, r"\2 \1, M.D. is a heart doctor", my_string)

In the pattern we specify two groups, and then we use them in the substituting by referencing them with \1 and \2



来源:https://stackoverflow.com/questions/51644998/extracting-name-as-first-name-last-name-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!