问题
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