首页 > 解决方案 > 将具有类似字典表示的字符串转换为 Python 中的字典

问题描述

假设我有一个看起来像这样的字符串:

text = '''
{"question":"In 2017, what was the approximate number of clinics in the US that provided abortion services?","category":"RFB","answers":["80","800","8000","80000"],"sources":["https://www.guttmacher.org/fact-sheet/induced-abortion-united-states"]} 
{"question":"Compared to actively religious US adults, how many unaffiliated US adults were active in non-religious voluntary organizations, such as charities?","category":"DFB","answers":["Slightly fewer (10% difference)","Slightly more (10% difference)","Many fewer (35% difference)","Many more (35% difference)"],"sources":["https://www.pewforum.org/2019/01/31/religions-relationship-to-happiness-civic-engagement-and-health-around-the-world/"]}
{"question":"In the US in 2015, there were ___ abortions per 1000 live births.","category":"DFB","answers":["12","80","124","188"],"sources":["https://www.cdc.gov/mmwr/volumes/67/ss/ss6713a1.htm?s_cid=ss6713a1_w"]}'''

我想将此字符串转换为带有“问题”、“类别”、“答案”和“来源”键的 Python 字典。 Questionandcategory将始终是纯文本,而answersandsources将采用带括号的类似列表的格式。

我认为它需要使用正则表达式,如this answer中的某种形式dictionary = dict(re.findall(r"\{(\S+)\s+\{*(.*?)\}+",text)),但不能完全匹配我需要的所有键。

有什么想法吗?

确定的“重复”链接不能解决我的问题。使用时出现“无效语法”错误dictionary = ast.literal_eval(text),因为我没有成功地将所有单独的字典与字符串分开。

标签: python

解决方案


你可以试试这个,希望对你有帮助。我在这里返回一个列表,但这取决于你的目的。

a = text.strip().split("\n")
import ast
b = []
for i in a:
    d = dict(ast.literal_eval(i))
    b.append(d)
>>>b
[{'question': 'In 2017, what was the approximate number of clinics in the US that provided abortion services?', 'category': 'RFB', 'answers': ['80', '800', '8000', '80000'], 'sources': ['https://www.guttmacher.org/fact-sheet/induced-abortion-united-states']}, {'question': 'Compared to actively religious US adults, how many unaffiliated US adults were active in non-religious voluntary organizations, such as charities?', 'category': 'DFB', 'answers': ['Slightly fewer (10% difference)', 'Slightly more (10% difference)', 'Many fewer (35% difference)', 'Many more (35% difference)'], 'sources': ['https://www.pewforum.org/2019/01/31/religions-relationship-to-happiness-civic-engagement-and-health-around-the-world/']}, {'question': 'In the US in 2015, there were ___ abortions per 1000 live births.', 'category': 'DFB', 'answers': ['12', '80', '124', '188'], 'sources': ['https://www.cdc.gov/mmwr/volumes/67/ss/ss6713a1.htm?s_cid=ss6713a1_w']}]


推荐阅读