+-
从包含键值对的字符串中获取python字典
我有一个格式的 python字符串:

str = "name: srek age :24 description: blah blah"

有没有办法将它转换为看起来像的字典

{'name': 'srek', 'age': '24', 'description': 'blah blah'}  

其中每个条目都是从字符串中取出的(键,值)对.我尝试将字符串拆分为列表

str.split()  

然后手动删除:,检查每个标签名称,添加到字典中.这种方法的缺点是:这个方法很讨厌,我必须手动删除:对于每一对,如果字符串中有多个单词’value'(例如,blah blah for description),每个单词将是一个单独的条目一个不可取的清单.是否有任何Pythonic方式获取字典(使用python 2.7)?

最佳答案
>>> 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'}

说明:

\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
点击查看更多相关文章

转载注明原文:从包含键值对的字符串中获取python字典 - 乐贴网