首页 > 解决方案 > 从python中的字符串中提取名称

问题描述

首先,目的是仅将名称与由韩文名称、英文名称、特殊字符(-、*、逗号)、空格等组成的字符串区分开来,如果名称重复则只留下一个。

所以,到目前为止我所做的是我已经获取了一个文本文件并将其转换为一个字符串,消除了不必要的特殊字符。

import re

path = 'E:\Data Science\Personal_Project\Church\Data\original.txt'

def open_text(path):
    with open(path, "r", encoding='euc-kr') as f:
        text = f.readlines()
        string = ''.join(text)
        unicode_line = string.translate({ord(c): None for c in '.;*\n'})
        cleaned = re.split('-|', unicode_line)


print(unicode_line, type(cleaned))
return(cleaned)

这是问题。我想在上面的函数中添加什么

1)如果虚线前面有一个字母(例如,“出席 ---”),我想删除它前面的文本(ei,“出席”),然后将其拆分为破折号。

2) 或者我想列出一个列表——[出勤、退房、假期]——我想删除列表中包含的单词。

如果您能告诉我一种更好的方法或更pythonic的方法,我将不胜感激!

为了您的方便,我将添加一个示例文本。

Status of January 20th




** Attendance
-----------

John Smith, John Smith, Bob Smith, Mike Smith, Jane Jones, Daniel Lee, Dong Jones, Jeannie Jones, Jessica Yi, McAleer Chung, Shu K Smith, Song Kim, Steve Carlos, Bob Smith





** Absent
---------

holiday, unauthorized, unpaid leave, emergency
------------------------------------------------------------------------------------------- 
Brown Williams, Paul Garcia

此外,这是我想要的输出,只有不重复的名称。如果您在上面看到,有两个 John Smith 和两个 Bob Smith。最后,如果我能按字母顺序得到它,那就太棒了。

Output:


John Smith, Bob Smith, Mike Smith, Jane Jones, Daniel Lee, Dong Jones, Jeannie Jones, Jessica Yi, McAleer Chung, Shu K Smith, Song Kim, Steve Carlos, Brown Williams, Paul Garcia

标签: pythonregexstring

解决方案


如果我对您的理解正确,您希望获取set文档中所有名称的名称,在某些标题行中没有单词,并且在预定义的非名称单词列表中没有单词,例如“假期”。

首先,我建议不要加入所有行,然后您可以检查一行是否以-or开头*并排除该行。它还可以更轻松地跳过带有标题的第一行。然后,您可以定义您的非名字单词列表,遍历文件中的行并用,.

non_names = set("holiday, unauthorized, unpaid leave, emergency".split(", "))
with open("text.txt") as f:
    next(f) # skip first line
    names = set()
    for line in f:
        if not line.startswith(("*", "-")):
            for name in line.strip().split(", "):
                if name and name not in non_names:
                    names.add(name)

或者set直接在复杂的生成器表达式上使用:

    names = set(name for line in f
                     if not line.startswith(("*", "-"))
                     for name in line.strip().split(", ")
                     if name and name not in non_names)

两种方式,结果都是{'John Smith', 'Jeannie Jones', 'Mike Smith', 'Bob Smith', 'McAleer Chung', 'Steve Carlos', 'Brown Williams', 'Jessica Yi', 'Paul Garcia', 'Jane Jones', 'Shu K Smith', 'Song Kim', 'Daniel Lee', 'Dong Jones'}。要获得排序后的名称,只需对 进行排序set,或者如果要按姓氏排序,请使用特殊key函数:

names = sorted(names, key=lambda s: s.split()[-1])

推荐阅读