python字典从字符串转换?
如果我有像
"{ 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果 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.
修复输入将是最好的解决方案。
但是您可以跳过一系列的步骤来尝试使输入可解析
json
。这是脆弱的,因为您的输入并不完全是 json,并且不同的输入可能很容易破坏它(尽管在我看来,它仍然优于平淡使用eval
)。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 ofeval
).如果是一些外部数据,请不要对其使用
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/复制自
编辑< /strong>
您可以使用正则表达式
copied from
EDIT
You can use regular expressions
您可以替换或删除任何不需要的字符
,然后将字符串分成两部分以创建字典
或更新
you could replace or delete any unwanted character
and then split the string in two to create a dict
or update