0

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
0

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much
A small correction, just replace M.D. with . because the format is not same everytime in the data which I have print(re.sub(r"([a-z'-]+), ([a-z'-]+)(?=,\s*.)", r'\2 \1', data, flags=re.IGNORECASE))
0
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

Comments

0

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

1 Comment

it will fail if it would be "Acosta, Christina, PT is a heart doctor". I appreciate the help. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.