让我们在这里使用re.findall
:
>>> import re
>>> dict(re.findall(r'(?=\S|^)(.+?): (\S+)', text))
{'Date': '07/14/1995', 'Subject text': 'Something-cool', 'Time': '11:31:50'}
或者,如果您坚持使用这种格式,
>>> {k : [v] for k, v in re.findall(r'(?=\S|^)(.+?): (\S+)', text)}
{
'Date' : ['07/14/1995'],
'Subject text': ['Something-cool'],
'Time' : ['11:31:50']
}
细节
(?= # lookahead
\S # anything that isn't a space
| # OR
^ # start of line
)
(.+?) # 1st capture group - 1 or more characters, until...
: # ...a colon
\s # space
(\S+) # 2nd capture group - one or more characters that are not wsp
语义上,这个正则表达式的意思是“给我所有符合特定模式的项对,该模式由某些内容、冒号和空格以及一堆非空格字符组成”。开始的前瞻是为了避免捕获前导空格(而且回溯只支持固定宽度的断言)。
请注意:如果值中有空格,则此方法将失败。
如果您要在文本文件中处理多行数据,可以基于此正则表达式并使用defaultdict。
from collections import defaultdict
d = defaultdict(list)
with open(file) as f:
for text in file:
for k, v in re.findall(r'(?=\S|^)(.+?): (\S+)', text.rstrip()):
d[k].append(v)
这将在给定的键上为您的字典添加一个或多个值。
text.split(": ")
中对每个值(除了第一个和最后一个)进行.split(' ')
,然后将第一个结果作为值,其余作为键。 - Jordan A.