gpt4 book ai didi

python - 使用带冒号的字符串创建字典

转载 作者:行者123 更新时间:2023-11-28 22:56:31 25 4
gpt4 key购买 nike

假设有一个字符串 s,它看起来像这样:

s = 'Title: A title Date: November 23 1234 Other: Other information'

是否可以创建一个字典:

{'Title':'A title','Date':'November 23 1234','Other':'Other information'}

起初我想简单地在冒号所在的位置拆分它,但是后来,不知道 Title 的值可能是什么,标题本身可能有冒号。唉,这个信息的来源也没有用逗号分隔,所以这也很痛苦。例如,你怎么也可以这样做:

s = 'Title: Example: of a title Date: November 23 1234 Other: Other information'

该示例中的标题是 Example: of a title

我检查过 this question , 但它没有回答我的问题。

提前致谢。

最佳答案

import re
from itertools import izip

s = 'Title: Example: of a title Date: November 23 1234 Other: Other information'

keys = ['Title', 'Date', 'Other']
pattern = re.compile('({})\s+'.format(':|'.join(keys)))

print dict(izip(*[(i.strip() for i in (pattern.split(s)) if i)]*2))

输出:

{'Date:': 'November 23 1234 ',
'Other:': 'Other information',
'Title:': 'Example: of a title '}

关于python - 使用带冒号的字符串创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15471311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com