将名字提取为 python 中的名字和姓氏

Extracting name as first name last name in python

我有一个包含以下行的文本文件:

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

Alissa Russo, M.D. is a heart doctor

有没有办法转换下面的行:

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

Christina Acosta, M.D. is a heart doctor

预期输出:

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

您可以使用以下正则表达式对名字和姓氏进行分组,并在不带逗号的情况下以相反的顺序替换它们:

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' ', data, flags=re.IGNORECASE))

这输出:

Christina Acosta, M.D. is a heart doctor
Alissa Russo, M.D. is a heart doctor
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

你的输出应该是:Christina Acosta, M.D. is a heart doctor

试试这个

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" , M.D. is a heart doctor", my_string)

在模式中我们指定了两个组,然后我们通过用 </code> 和 <code>

引用它们来在替换中使用它们