我在 python 中有以下字符串:
Date: 07/14/1995 Time: 11:31:50 Subject text: Something-cool
我想用下面的 key: [value]
dict()
{"Date":["07/13/1995"], "Time": ["11:31:50"], "Subject text":["Something-cool"]}
如果我用 :
拆分字符串,我会得到以下结果。我怎样才能得到上述期望的结果?
>>> text.split(": ")
['Date', '07/14/1995 Time', '11:31:50 Subject text', 'Something-cool']
最佳答案
让我们在这里使用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)
这将为您的字典中的给定键添加一个或多个值。
关于python - 拆分字符串并生成键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50548728/