python - 拆分字符串并生成键值对

标签 python string dictionary split

我在 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/

相关文章:

python - 删除所选项目上的虚线矩形

python - 将文本文件中的 block 读入二维数组

c# - 无法将 keyValuePair 直接添加到 Dictionary

C++ STL 映射,其键为 shared_ptr<struct tm>

python - 如何删除空数据行

python - 从 QuerySet 获取原始 SQL 查询

c# - 在 C# 中获取当前月份数的最佳方法

python - 错误列表索引必须是整数或切片,而不是 str

c - 坚持向字符串添加字符

python - 如何比较字典列表中的多个键值?