用带冒号的字符串创建字典
假设我们有一个字符串,s,长得像这样:
s = 'Title: A title Date: November 23 1234 Other: Other information'
我们能不能创建一个字典,内容是:
{'Title':'A title','Date':'November 23 1234','Other':'Other information'}
一开始我想直接在冒号的地方把它分开,但我不知道标题的值可能是什么,所以标题里可能也会有冒号。更糟糕的是,这些信息的来源也没有用逗号来分隔,所以这就更麻烦了。比如,像下面这种情况,我们该怎么处理:
s = 'Title: Example: of a title Date: November 23 1234 Other: Other information'
在这个例子中,标题是 Example: of a title
。
我查过 这个问题,但它没有回答我的疑问。
提前谢谢你。
3 个回答
0
你不能仅仅通过冒号来分割,因为可能有多个冒号,而且它们可能是嵌套在一起的。
如果关键词(Title
、Date
、Other
)是固定的,你可以试试下面这个正则表达式:
import re
reg_ex = re.compile("Title\:(.+)Date\:(.+)Other\:(.+)")
reg_ex.match(s).groups() #(' A title ', ' November 23 1234 ', ' Other information')
1
你可以用正则表达式来实现这个功能:
>>> import re
>>>
>>> s = 'Title: A title Date: November 23 1234 Other: Other information'
>>> matches = re.findall(r'(\w+): ((?:\w+\s)+)', s)
>>>
>>> dict(matches)
{'Date': 'November 23 1234 ', 'Other': 'Other ', 'Title': 'A title '}
3
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 '}