开发者

python dictionary conversion from string?

if I've string like

"{ partner_name = test_partner}" OR " { partner_name : test_partner }

its an example string will be very complex with several special characters included like =, [ , ] , { , }

what will be the best way to convert it into a python object - so I can process it

I tri开发者_Python百科ed with eval but it requires " ' " for string, but how can we add this special character \' before starting and ending of every word, I tried regular express re.findal('\w+') but it fails when my string contains ' _ ' or like characters as it will separate the string by ' _ '

Object of this question is my application needs, user friendly language as input - and I thought Json Dict will be good - but user is lazzy to put " ' " before and after of each string...

then I thought for yaml but its also complex, if anybody can suggest better user friendly input which I use as python object - then please help me out.


If YAML is too complex for your users, you should perhaps think about giving them a structured input form and formatting the data correctly from there. YAML is pretty much as easy to write as possible for specifying structures, certainly easier than the curly braces syntax.


Fixing the input would be the best solution.

But you could jump through a series of hoops in an attempt to make the input parsable by json. This is fragile since your input isn't json exactly and diverging input could break this easily (although it's still imo to be preferred over bland use of eval).

>>> import json
>>> s = '{ partner_name = test_partner}'
>>> t = s.replace(' ', '') # strip whitespace
>>> t = t.replace('=', '":"')
>>> t = t.replace('{','{"')
>>> t = t.replace('}','"}')
>>> json.loads(t)
{u'partner_name': u'test_partner'}


If it's some outside data, do not use eval() on it! If you want to parse it properly, have a look at some parsing libraries. The ones using parsing combinators are quite nice - for example https://github.com/pyparsing/pyparsing Or maybe a peg parser: http://fdik.org/pyPEG/


>>> import ast

>>> ast.literal_eval("{ 'partner_name' : 'test_partner' }")
{'partner_name': 'test_partner'}

copied from

EDIT

You can use regular expressions

>>> import re
>>> m = re.match(r"(?P<partner_name>\w+) = (?P<test_partner>\w+)", "foo = bar")
>>> m.groupdict()
{'partner_name': 'foo', 'test_partner': 'bar'}
>>> 


you could replace or delete any unwanted character

>>> s
'{ partner_name = test_partner }'
>>> s = ''.join([c for c in s.replace('=', ':') if not c in '\ {}'])
>>> s
'partner_name:test_partner'

and then split the string in two to create a dict

>>> dict([s.split(':')])
{'partner_name': 'test_partner'}

or update

>>> your_dict.update([s.split(':')])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜