【问题标题】:Extracting name as first name last name in python在python中提取名字作为名字姓氏
【发布时间】:2018-08-02 03:18:52
【问题描述】:

我有一个文本文件,其行如下:

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

【问题讨论】:

    标签: regex python-3.x spacy data-extraction


    【解决方案1】:

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

    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))
    

    这个输出:

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

    【讨论】:

    • 非常感谢
    • 一个小修正,只需将 M.D. 替换为 .因为每次打印的数据中的格式都不相同 print(re.sub(r"([a-z'-]+), ([a-z'-]+)(?=,\s*. )", r'\2 \1', 数据, flags=re.IGNORECASE))
    【解决方案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
    

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

    【讨论】:

      【解决方案3】:

      试试这个

      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)
      

      在模式中,我们指定了两个组,然后我们通过 \1\2 引用它们来替换它们

      【讨论】:

      • 如果是“Acosta, Christina, PT is a heart doctor”,它将失败。我很感激帮助。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      相关资源
      最近更新 更多