Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python中的名称解析姓氏_Python_Pandas - Fatal编程技术网

从Python中的名称解析姓氏

从Python中的名称解析姓氏,python,pandas,Python,Pandas,正在尝试确定单个姓氏 names = ["John Smith", "D.J. Richies III","AJ Hardie Jr.", "Shelia Jackson-Lee", "Bob O'Donnell"] 期望输出 last_names = ['Smith', 'Richies','Hardie','Lee', 'ODonnell' ] 我希望有一个现有的库或代码集可以轻松地处理这些更罕见/奇怪的情况 谢谢你的帮助 您可以尝试以下方法: names = ["John Smith"

正在尝试确定单个姓氏

names = ["John Smith", "D.J. Richies III","AJ Hardie Jr.", "Shelia Jackson-Lee", "Bob O'Donnell"]
期望输出

last_names = ['Smith', 'Richies','Hardie','Lee', 'ODonnell' ]
我希望有一个现有的库或代码集可以轻松地处理这些更罕见/奇怪的情况

谢谢你的帮助

您可以尝试以下方法:

names = ["John Smith", "D.J. Richies III","AJ Hardie Jr.", "Shelia Jackson-Lee", "Bob O'Donnell"]

suffixes = ["II", "Jr.", "III", "Sr."]

last_names = []

for i in names:
    new_name = i.split()
    if len(new_name) == 2 and "-" in new_name[1]:
         last_names.append(new_name[1].split("-")[1])

    elif len(new_name) == 2:
          last_names.append(new_name[1])

    else:
        if new_name[-1] in suffixes:
           last_names.append(new_name[1])

print(last_names)
输出将包含姓氏:

['Smith', 'Richies', 'Hardie', 'Lee', "O'Donnell"]
处理名字很难 简单的字符串操作解决方案最终会失败。你开始通过后缀(
III
Jr.
)意识到这一点,但是像
de la Paz
这样的复合姓氏呢

你想要:


您可以使用nameparser包。有关更多示例,您可以查看:

输出为:

                 Name title   first middle         last suffix nickname
0          John Smith          John               Smith                
1    D.J. Richies III          D.J.             Richies    III         
2       AJ Hardie Jr.            AJ              Hardie    Jr.         
3  Shelia Jackson-Lee        Shelia         Jackson-Lee                
4       Bob O'Donnell           Bob           O'Donnell          
因此,如果您只想知道姓氏:

df['last']
你会得到:

0          Smith
1        Richies
2         Hardie
3    Jackson-Lee
4      O'Donnell
Name: last, dtype: object

要求人们推荐图书馆通常被认为是不合适的。你试过什么?看起来您只需要在
str.split()
之后取第二个单词并删除标点符号,这对于标准字符串函数来说是非常简单的。问题在于连字符的名称。我理解你的意思,因为它可以是两个拆分(第二个是包含连字符的名称),然后是一个压缩。只是不知道是否有一个我不知道存在的所有人都在使用的库(对Python来说是相当新的)?或者姓氏是两个没有连字符的标记?实际上,在这里可以问一个库。处理应用程序中的名字比大多数人意识到的要难,如果有人把这样的东西放进了一个图书馆,我也不会感到惊讶。我认为没有中间名字,因为这些名字是从网站上刮下来的。我没有所有的例子,但在看了几百个之后,似乎没有,这就是为什么我认为AChampion的解决方案可能有效的原因。这可以与一个要剥离的后缀列表相结合。
df['last']
0          Smith
1        Richies
2         Hardie
3    Jackson-Lee
4      O'Donnell
Name: last, dtype: object