【问题标题】:Regex for name extraction on text file用于文本文件名称提取的正则表达式
【发布时间】:2014-10-04 08:26:28
【问题描述】:

我有一个包含作者和摘要列表的纯文本文件,我正在尝试仅提取作者姓名以用于网络分析。我的文本遵循这种模式,包含 500 多个摘要:

2010 - NUCLEAR FORENSICS OF SPECIAL NUCLEAR MATERIAL AT LOS ALAMOS: THREE RECENT STUDIES 

Purchase this article

David L. Gallimore, Los Alamos National Laboratory

Katherine Garduno, Los Alamos National Laboratory

Russell C. Keller, Los Alamos National Laboratory

Nuclear forensics of special nuclear materials is a highly specialized field because there are few analytical laboratories in the world that can safely handle nuclear materials, perform high accuracy and precision analysis using validated analytical methods.

我正在使用 Python 2.7.6 和 re 库。

我试过了

regex = re.compile(r'( [A-Z][a-z]*,+)')
print regex.findall(text)

仅提取姓氏,以及摘要中逗号之前的任何大写单词。

使用(r'.*,') 可以完美地提取全名,但也可以获取我不需要的整个摘要。

也许正则表达式是错误的方法?任何帮助或想法表示赞赏。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    如果您尝试匹配名称,我会尝试匹配整个子字符串而不是其中的一部分。

    您可以使用以下正则表达式并根据需要对其进行修改。

    >>> regex = re.compile(r'\b([A-Z][a-z]+(?: [A-Z]\.)? [A-Z][a-z]+),')
    >>> print regex.findall(text)
    ['David L. Gallimore', 'Katherine Garduno', 'Russell C. Keller']
    

    Working Demo | Explanation

    【讨论】:

    • 正是我想要的。谢谢!!
    • @hwnd 我喜欢你用工作演示和解释的链接构建帖子的方式。
    【解决方案2】:

    试试这个

    [A-Za-z]* ?([A-Za-z]+.) [A-Za-z]*(?:,+)
    

    它使中间名可选,并且通过将逗号放在非捕获组中来从结果中排除逗号

    【讨论】:

    • 似乎把所有东西都抽出来了一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多