sre*_*rek 8 python string dictionary
我有一个格式的python字符串:
str = "name: srek age :24 description: blah blah"
Run Code Online (Sandbox Code Playgroud)
有没有办法将它转换为看起来像的字典
{'name': 'srek', 'age': '24', 'description': 'blah blah'}
Run Code Online (Sandbox Code Playgroud)
其中每个条目都是从字符串中取出的(键,值)对.我尝试将字符串拆分为列表
str.split()
Run Code Online (Sandbox Code Playgroud)
然后手动删除:,检查每个标记名称,添加到字典.这种方法的缺点是:这种方法很讨厌,我必须手动删除:每一对,如果字符串中有多个单词'value'(例如,blah blahfor description),则每个单词将成为列表中的单独条目,即不可取.是否有任何Pythonic方式获取字典(使用python 2.7)?
Tim*_*ker 34
>>> r = "name: srek age :24 description: blah blah"
>>> import re
>>> regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
>>> d = dict(regex.findall(r))
>>> d
{'age': '24', 'name': 'srek', 'description': 'blah blah'}
Run Code Online (Sandbox Code Playgroud)
说明:
\b # Start at a word boundary
(\w+) # Match and capture a single word (1+ alnum characters)
\s*:\s* # Match a colon, optionally surrounded by whitespace
([^:]*) # Match any number of non-colon characters
(?= # Make sure that we stop when the following can be matched:
\s+\w+\s*: # the next dictionary key
| # or
$ # the end of the string
) # End of lookahead
Run Code Online (Sandbox Code Playgroud)
没有re:
r = "name: srek age :24 description: blah blah cat: dog stack:overflow"
lis=r.split(':')
dic={}
try :
for i,x in enumerate(reversed(lis)):
i+=1
slast=lis[-(i+1)]
slast=slast.split()
dic[slast[-1]]=x
lis[-(i+1)]=" ".join(slast[:-1])
except IndexError:pass
print(dic)
{'age': '24', 'description': 'blah blah', 'stack': 'overflow', 'name': 'srek', 'cat': 'dog'}
Run Code Online (Sandbox Code Playgroud)