python字典从字符串转换?

发布于 2024-08-31 15:13:17 字数 498 浏览 5 评论 0原文

如果我有像

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

它这样的字符串,那么示例字符串将非常复杂,其中包含几个特殊字符,例如=,[,],{,}

将其转换为python对象的最佳方法是什么 - 所以我可以处理它

我尝试过使用 eval 但它需要“ ' ”作为字符串,但是我们如何在每个单词的开始和结束之前添加这个特殊字符 \',我尝试了正则表达式 re.findal('\w+') 但当我的字符串包含 ' 时它会失败_ ' 或类似的字符,因为它将用 ' _ ' 分隔字符串

这个问题的对象是我的应用程序需求,用户友好的语言作为输入 - 我认为 Json Dict 会很好 - 但用户很懒,在 和 之前放置“ '”在每个字符串之后...

然后我想到了 yaml,但它也很复杂,如果有人可以建议我用作 python 对象的更好的用户友好输入 - 那么请帮助我。

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 tried 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

从来不烧饼 2024-09-07 15:13:17

如果 YAML 对于您的用户来说太复杂,您也许应该考虑为他们提供结构化输入表单并从那里正确格式化数据。 YAML 对于指定结构来说非常容易编写,当然比花括号语法更容易。

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.

瞄了个咪的 2024-09-07 15:13:17

修复输入将是最好的解决方案。

但是您可以跳过一系列的步骤来尝试使输入可解析 json。这是脆弱的,因为您的输入并不完全是 json,并且不同的输入可能很容易破坏它(尽管在我看来,它仍然优于平淡使用 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'}

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'}
南巷近海 2024-09-07 15:13:17

如果是一些外部数据,请不要对其使用eval()!如果你想正确解析它,请查看一些解析库。使用解析组合器的非常好 - 例如 https://github.com/pyparsing/pyparsing或者也许是一个钉解析器: http://fdik.org/pyPEG/

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/

仅此而已 2024-09-07 15:13:17
>>> import ast

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

复制自

编辑< /strong>

您可以使用正则表达式

>>> import re
>>> m = re.match(r"(?P<partner_name>\w+) = (?P<test_partner>\w+)", "foo = bar")
>>> m.groupdict()
{'partner_name': 'foo', 'test_partner': 'bar'}
>>> 
>>> 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'}
>>> 
韵柒 2024-09-07 15:13:17

您可以替换或删除任何不需要的字符

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

,然后将字符串分成两部分以创建字典

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

或更新

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

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(':')])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文