【问题标题】:Python3 - transform a complex string to a list/dictionary [duplicate]Python3 - 将复杂的字符串转换为列表/字典[重复]
【发布时间】:2019-09-11 03:28:50
【问题描述】:

我有一个这样的字符串:

l1="[{'t_steps': '', 't_expected': '', 't_type': 'Functional', 't_precond': 'xxx', 't_notes': 'test note', 't_name': 'First test'}]"

我需要将它转换为一个真正的列表对象,例如:

l1=[{'t_steps': '', 't_expected': '', 't_type': 'Functional', 't_precond': 'xxx', 't_notes': 'test note', 't_name': 'First test'}]

我试过了:

l1=list(l1)

l1=l1.split(',')

但结果并不好。 请问有人可以帮我把我的字符串转换成python可以读取的形式吗?

提前非常感谢

【问题讨论】:

  • import ast; l1 = ast.literal_eval(string)

标签: python python-3.x list dictionary


【解决方案1】:

使用eval

l1="[{'t_steps': '', 't_expected': '', 't_type': 'Functional', 't_precond': 'xxx', 't_notes': 'test note', 't_name': 'First test'}]"

这样做:

l1 = eval(l1)
l1

输出:

[{'t_steps': '', 't_expected': '', 't_type': 'Functional', 't_precond': 'xxx', 't_notes': 'test note', 't_name': 'First test'}]

【讨论】:

  • 您好,非常感谢,问题是当字符串包含这样的空值时:'[{"tk_kval": "yyy", "tk_kgroup": null, "tk_descr": "Create key ", "t_owner": 1}]'
  • 我不太明白你的意思,你能解释一下吗?
  • 如果你运行 l1=eval('[{"tk_kval": "yyy", "tk_kgroup": null, "tk_descr": "创建密钥", "t_owner": 1}]')你得到一个错误,因为空值
【解决方案2】:

使用json 的替代解决方案:

import json

l1="[{'t_steps': '', 't_expected': '', 't_type': 'Functional', 't_precond': 'xxx', 't_notes': 'test note', 't_name': 'First test'}]"
l2 = json.loads(l1)

【讨论】:

  • 这行不通。 JSON 应该使用 " 而不是 ' 才能正常工作。您可以使用 l1.replace("'","\"") 但这将是一个 hack 而不是实际的解决方案。
  • 嗯,是的,感谢您的指出。需要先将单引号替换为双引号。对我来说,它看起来仍然比通过 ast 评估更自然(这似乎是一个肮脏的 hack)。但口味不同!
  • 有一个内置的可用eval 与@xiutiqianshi 指出的工作相同
【解决方案3】:

这里的代码你可以解析。

x = "[{'t_steps': '', 't_expected': '', 't_type': 'Functional', 't_precond': 'xxx', 't_notes': 'test note', 't_name': 'First test'}]"
import re
# remove the [] and {} from the string
x = x.replace('[',"").replace("]","").replace("{","").replace("}","")
# split the string considering ',' and ite will return a list
x = x.split(",")
new_dict ={}
for values in x:
    # remove the "'" from the string
    values = re.sub("'*", '', values)
    values = values.replace('"', '')
    # split the key value pair from the list ':' and
    key, value = values.split(":")
    key = key.strip()
    value = value.strip()
    if value == "null":
        value = None
    else:
        # parsing the string value ton int or float
        try:
            if "." in value:
                value = float(value)
            else:
                value = int(value)
        except:
            pass
    new_dict[key.strip()] = value
final_list = []
final_list.append(new_dict)
print(final_list)

【讨论】:

  • 您好,非常感谢,问题是当字符串包含这样的空值时:'[{"tk_kval": "yyy", "tk_kgroup": null, "tk_descr": "Create key ", "t_owner": 1}]'
  • @ManuelSanti 我已经更新了答案。请检查。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2015-10-24
相关资源
最近更新 更多