我有一个包含数据的文本文件,如下所示。我必须从中提取一些必需的名称。我正在尝试以下代码,但未获得所需的结果。
该文件包含以下数据:
Leader : Tim Lee ; 34567
Head\Organiser: Sam Mathews; 11:53 am
Head: Alica Mills; 45612
Head\Secretary: Maya Hill; #53190
Captain- Jocey David # 45123
Vice Captain:- Jacob Green; -65432
我正在尝试的代码:
import re
pattern = re.compile(r'(Leader|Head\\Organiser|Captain|Vice Captain).*(\w+)',re.I)
matches=pattern.findall(line)
for match in matches:
print(match)
预期输出:
Tim Lee
Sam Mathews
Jocey David
Jacob Green
答案 0 :(得分:3)
import re
line = '''
Leader : Tim Lee ; 34567
Head\Organiser: Sam Mathews; 11:53 am
Head: Alica Mills; 45612
Head\Secretary: Maya Hill; #53190
Captain- Jocey David # 45123
Vice Captain:- Jacob Green; -65432'''
pattern = re.compile(r'(?:Leader|Head(?:\\Organiser|\\Secretary)?|Captain|Vice Captain)\W+(\w+(?:\s+\w+)?)',re.I)
matches=pattern.findall(line)
for match in matches:
print(match)
说明:
(?: : start non capture group
Leader : literally
| : OR
Head : literally
(?: : start non capture group
\\Organiser : literally
| : OR
\\Secretary : literally
)? ! end group, optional
| : OR
Captain : literally
| : OR
Vice Captain : literally
) : end group
\W+ : 1 or more non word character
( : start group 1
\w+ : 1 or more word char
(?: : non capture group
\s+ : 1 or more spaces
\w+ : 1 or more word char
)? : end group, optional
) : end group 1
给定示例的结果
Tim Lee
Sam Mathews
Alica Mills
Maya Hill
Jocey David
Jacob Green
答案 1 :(得分:1)
给出:
s='''\
Leader : Tim Lee ; 34567
Head\Organiser: Sam Mathews; 11:53 am
Head: Alica Mills; 45612
Head\Secretary: Maya Hill; #53190
Captain- Jocey David # 45123
Vice Captain:- Jacob Green; -65432'''
您可以这样获得名称:
>>> [e.rstrip() for e in re.findall(r'[:-]+[ \t]+(.*?)[;#]',s)]
['Tim Lee', 'Sam Mathews', 'Alica Mills', 'Maya Hill', 'Jocey David', 'Jacob Green']
或者,创建标题和相关名称的字典:
>>> {k:v.rstrip() for k,v in re.findall(r'^\s*(Leader|Head\\Organiser|Head|Head\\Secretary|Captain|Vice Captain)\s*[:-]+[ \t]+(.*?)[;#]',s, re.M)}
{'Leader': 'Tim Lee', 'Head\\Organiser': 'Sam Mathews', 'Head': 'Alica Mills', 'Head\\Secretary': 'Maya Hill', 'Captain': 'Jocey David', 'Vice Captain': 'Jacob Green'}
然后可以将其限制为所需的标题:
>>> {k:v.rstrip() for k,v in re.findall(r'^\s*(Leader|Head\\Organiser|Captain|Vice Captain)\s*[:-]+[ \t]+(.*?)[;#]',s, re.M)}
{'Leader': 'Tim Lee', 'Head\\Organiser': 'Sam Mathews', 'Captain': 'Jocey David', 'Vice Captain': 'Jacob Green'}
如果您只想使用名称(Python 3.6+会保持顺序,因此它们将按字符串顺序排列):
>>> {k:v.rstrip() for k,v in re.findall(r'^\s*(Leader|Head\\Organiser|Captain|Vice Captain)\s*[:-]+[ \t]+(.*?)[;#]',s, re.M)}.values()
dict_values(['Tim Lee', 'Sam Mathews', 'Jocey David', 'Jacob Green'])