Extract Python dictionary from string

…衆ロ難τιáo~ 提交于 2020-08-04 09:48:14

问题


I have a string with valid python dictionary inside

data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc."

I need to extract that dict. I tried with regex but for some reason re.search(r"\{(.*?)\}", data) did not work. Is there any better way extract this dict?


回答1:


From @AChampion's suggestion.

>>> import re
>>> import ast
>>> x = ast.literal_eval(re.search('({.+})', data).group(0))
>>> x
{'Bar': 'value', 'Foo': '1002803'}

so the pattern you're looking for is re.search('({.+})', data)

You were supposed to extract the curly braces with the string, so ast.literal_eval can convert the string to a python dictionary . you also don't need the r prefix as { or } in a capturing group, () would be matched literally.




回答2:


Your solution works!

In [1]: import re

In [2]: data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc."

In [3]: a = eval(re.search(r"\{(.*?)\}", data).group(0))

In [4]: a
Out[4]: {'Bar': 'value', 'Foo': u'1002803'}


来源:https://stackoverflow.com/questions/39807724/extract-python-dictionary-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!