2014-10-03 67 views
1

我有一個純文本文件,其中包含作者和摘要列表,我試圖提取僅用於網絡分析的作者名稱。我的文本遵循這種模式,幷包含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'.*,')完美地提取完整的名稱,但也抓住了我不需要的整個抽象。

也許正則表達式是錯誤的方法?任何幫助或想法表示讚賞。

回答

2

如果您試圖匹配名稱,我會嘗試匹配整個子字符串而不是它的一部分。

您可以使用以下正則表達式並在需要時進行修改。

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

+0

正是我一直在尋找從排除的結果逗號。謝謝!! – 2014-10-04 00:19:12

+0

@hwnd我喜歡你通過鏈接工作演示和解釋來構建你的文章的方式。 – Miller 2014-10-04 01:54:41

+0

@Miller謝謝=) – hwnd 2014-10-04 01:59:14

0

試試這個

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

這使得中間名可選,再加上它,將其置於一個非捕獲組

+0

似乎拉出一點點的一切。 – 2014-10-04 00:21:55