[英]Extract Python dictionary from string
I have a string with valid python dictionary inside我有一个包含有效 python 字典的字符串
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.我尝试使用正则表达式,但由于某种原因
re.search(r"\\{(.*?)\\}", data)
不起作用。 Is there any better way extract this dict?有没有更好的方法提取这个字典?
From @AChampion's suggestion. 来自@AChampion的建议。
>>> 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)
所以您要寻找的模式是
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 . 您应该使用字符串提取花括号,因此
ast.literal_eval
可以将字符串转换为python字典。 you also don't need the r
prefix as {
or }
in a capturing group, ()
would be matched literally. 您也不需要
r
前缀作为捕获组中的{
或}
, ()
将按字面值进行匹配。
Better way of parsing out the dictionary without having to use eval
:无需使用
eval
即可解析字典的更好方法:
import re
import json
dict_object = json.loads(re.search('({.+})', data).group(0).replace("'", '"'))
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'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.