更新答案
使用来自@martineau 和@ekhumoro 的cmet,以下编辑后的代码包含一个搜索字符串并提取所有有效dicts 的函数。这是对我之前回答的一种更稳健的方法,因为现实世界 dict 的内容可能会有所不同,而这个逻辑(希望)可以解释这一点。
示例代码:
import json
import re
def extract_dict(s) -> list:
"""Extract all valid dicts from a string.
Args:
s (str): A string possibly containing dicts.
Returns:
A list containing all valid dicts.
"""
results = []
s_ = ' '.join(s.split('\n')).strip()
exp = re.compile(r'(\{.*?\})')
for i in exp.findall(s_):
try:
results.append(json.loads(i))
except json.JSONDecodeError:
pass
return results
测试字符串:
OP 的原始字符串已更新为添加多个dicts、一个数值作为最后一个字段和一个list 值。
s = """
This is a {testing string} example
This {is} a testing {string} example
{"website": "stackoverflow",
"type": "question",
"date": 5
}
{"website": "stackoverflow",
"type": "question",
"date": "2020-09-11"
}
{"website": "stackoverflow",
"type": "question",
"dates": ["2020-09-11", "2020-09-12"]
}
This is a {testing string} example
This {is} a testing {string} example
"""
输出:
正如 OP 所述,字符串中通常只有一个 dict,因此(显然)可以使用 results[0] 访问。
>>> results = extract_dict(s)
[{'website': 'stackoverflow', 'type': 'question', 'date': 5},
{'website': 'stackoverflow', 'type': 'question', 'date': '2020-09-11'},
{'website': 'stackoverflow', 'type': 'question', 'dates': ['2020-09-11', '2020-09-12']}]
原答案:
忽略此部分。虽然代码有效,但它特别适合 OP 的要求,并且不适合其他用途。
此示例使用正则表达式来识别 dict start {" 和 dict end "} 并提取中间,然后将字符串转换为正确的 dict。随着新行的出现和正则表达式的复杂化,我只是将字符串展平以开始。
根据@jizhihaoSAMA 的评论,我已更新为使用json.loads 将字符串转换为dict,因为它更简洁。如果您不想额外导入,eval 也可以,但不推荐。
示例代码:
import json
import re
s = """
This is a {testing string} example
This {is} a testing {string} example
{"website": "stackoverflow",
"type": "question",
"date": "10-09-2020"
}
This is a {testing string} example
This {is} a testing {string} example
"""
s_ = ' '.join(s.split('\n')).strip()
d = json.loads(re.findall(r'(\{\".*\"\s?\})', s_)[0])
>>> d
>>> d['website']
输出:
{"website": "stackoverflow", "type": "question", "date": "10-09-2020"}
'stackoverflow'