更新的答案
从@martineau和@ekhumoro的评论中得到启发,下面编辑的代码包含一个函数,该函数搜索字符串并提取有效的所有字典。这是比我之前的答案更健壮的方法,因为现实世界中字典的内容可能会有所变化,而这个逻辑(希望)能够考虑到这一点。
示例代码:
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
测试字符串:
原始字符串已更新,添加了多个dict
、一个数字值作为最后一个字段和一个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
"""
输出:
正如原贴所述,通常在字符串中只有一个 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']}]
原始答案:
忽略此部分。虽然代码可以工作,但它仅适用于特定的请求,对于其他用途而言并不健壮。
此示例使用正则表达式识别字典开始 {"
和字典结束 "}
,提取中间内容,然后将字符串转换为合适的 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'
{
和}
字符的内容,所以您需要找到每个成对的字符,并检查它是否包含有效的字典(同时希望没有东西恰好看起来像是一个有效的字典)。 - martineau