0

我有一个字符串,里面有一堆奇怪的东西,我想把它分解成一个列表:

"44":{"1":4.6,"0":1.53,"2":7.2},"53":{"1":4.2,"0":1.4,"2":6.75},"121":{"1":3.2,"0":1.6,"2":6}

理想情况下,我想:

"44":{"1":4.6,"0":1.53,"2":7.2}
"53":{"1":4.2,"0":1.4,"2":6.75}
"121":{"1":3.2,"0":1.6,"2":6}

但我会满足于在每个 } 处拆分。

mystring.split('}')由于某种原因,似乎将我的字符串拆分为每个字符一个元素的列表。不知道我做错了什么。帮助!

4

6 回答 6

7

几乎看起来像有效的 JSON。

>>> s = '"44":{"1":4.6,"0":1.53,"2":7.2},"53":{"1":4.2,"0":1.4,"2":6.75},"121":{"1":3.2,"0":1.6,"2":6}'
>>> import json
>>> d = json.loads("{" + s + "}")
>>> d
{'53': {'2': 6.75, '0': 1.4, '1': 4.2}, '44': {'2': 7.2, '0': 1.53, '1': 4.6}, '
121': {'2': 6, '0': 1.6, '1': 3.2}}
>>> for key,value in d.items():
...    print("Key: {0} - Value: {1}".format(key,value))
...
Key: 53 - Value: {'2': 6.75, '0': 1.4, '1': 4.2}
Key: 44 - Value: {'2': 7.2, '0': 1.53, '1': 4.6}
Key: 121 - Value: {'2': 6, '0': 1.6, '1': 3.2}
于 2013-05-25T22:00:13.197 回答
1

你可以试试这个:

s = '"44":{"1":4.6,"0":1.53,"2":7.2},"53":{"1":4.2,"0":1.4,"2":6.75},"121":{"1":3.2,"0":1.6,"2":6}'
h = eval("{"+s+"}")
for k in h: print k,h[k]

但由于 eval 不安全,因为它可以执行任意代码,所以使用 literal_eval 会好得多。literal_eval 仅适用于有效数据类型:

from ast import literal_eval
s = # ....
h = literal_eval("{"+s+"}")
for k in h: print k,h[k]

输出

121 {'1': 3.2, '0': 1.6, '2': 6}
44 {'1': 4.6, '0': 1.53, '2': 7.2}
53 {'1': 4.2, '0': 1.4, '2': 6.75}
于 2013-05-25T22:00:37.320 回答
0

你可以这样做:

>>> string = '"44":{"1":4.6,"0":1.53,"2":7.2},"53":{"1":4.2,"0":1.4,"2":6.75},"121":{"1":3.2,"0":1.6,"2":6}'
>>> string.replace('},','}***').split('***')
['"44":{"1":4.6,"0":1.53,"2":7.2}', '"53":{"1":4.2,"0":1.4,"2":6.75}', '"121":      {"1":3.2,"0":1.6,"2":6}']
于 2013-05-25T22:08:53.210 回答
0

正确回答您的问题取决于允许使用哪种表达方式。如果表达式可能包含嵌套大括号,那么您需要递归正则表达式。以下解决方案不支持嵌套大括号,但足以解析您的示例:

    for token in re.findall(r'((?:[^{,]|{.*?})+)', mystring):
        print token
于 2013-05-25T22:09:37.447 回答
0

您的输入几乎是 JSON;这是一个字典的内容,只是缺少括号

import json
nearly_json = '"44":{"1":4.6,"0":1.53,"2":7.2},"53":{"1":4.2,"0":1.4,"2":6.75},"121":{"1":3.2,"0":1.6,"2":6}'

d = json.loads(f'{{ {nearly_json} }}') # Add the missing enclosing braces, and convert to Python (deserialize)...

d
{'44': {'1': 4.6, '0': 1.53, '2': 7.2}, '53': {'1': 4.2, '0': 1.4, '2': 6.75}, '121': {'1': 3.2, '0': 1.6, '2': 6}}

d['44']
{'1': 4.6, '0': 1.53, '2': 7.2}

正如 TimPietzcker 所说,您现在可以遍历字典,例如使用.items() 或者您可以访问其.keys()

于 2020-01-03T15:44:29.597 回答
-2

只是用逗号分开?

print '"44":{"1":4.6,"0":1.53,"2":7.2},"53":{"1":4.2,"0":1.4,"2":6.75},"121":{"1":3.2,"0":1.6,"2":6}'.split(',')

给出:

['"44":{"1":4.6', '"0":1.53', '"2":7.2}', '"53":{"1":4.2', '"0":1.4', '"2":6.75}', '"121":{"1":3.2', '"0":1.6', '"2":6}']

这就是你所要求的。

于 2013-05-25T22:23:28.770 回答