['precision recall f1-score support 0 0.95 0.96 0.96 10762 1 0.91 0.95 0.93 9339 2 0.90 0.59 0.71 1628 micro avg 0.93 0.93 0.93 21729 macro avg 0.92 0.83 0.87 21729 weighted avg 0.93 0.93 0.93 21729 samples avg 0.93 0.93 0.93 21729']转成这样的字典形式report1 = { '0': {'precision': 0.95, 'recall': 0.96, 'f1-score': 0.96, 'support': 10762}, '1': {'precision': 0.91, 'recall': 0.95, 'f1-score': 0.93, 'support': 9339}, '2': {'precision': 0.90, 'recall': 0.59, 'f1-score': 0.71, 'support': 1628}, 'micro avg': {'precision': 0.93, 'recall': 0.93, 'f1-score': 0.93, 'support': 21729}, 'macro avg': {'precision': 0.92, 'recall': 0.83, 'f1-score': 0.87, 'support': 21729}, 'weighted avg': {'precision': 0.93, 'recall': 0.93, 'f1-score': 0.93, 'support': 21729}, 'samples avg': {'precision': 0.93, 'recall': 0.93, 'f1-score': 0.93, 'support': 21729} }
时间: 2023-08-03 19:05:01 浏览: 130
你可以使用以下代码将这个字符串转换成你想要的字典形式:
```
import re
# 提取键值对
pairs = re.findall(r'(\S+)\s+([\d\.]+)', string)
# 将键值对转换成字典
result = {}
for i, pair in enumerate(pairs):
key, value = pair
if key.isdigit():
if key not in result:
result[key] = {}
result[key][pairs[i+1][0]] = float(pairs[i+1][1])
# 添加其他信息
for key in ['micro avg', 'macro avg', 'weighted avg', 'samples avg']:
if key not in result:
continue
result[key]['support'] = result['support']
result[key]['precision'] = result[key]['precision_score']
result[key]['recall'] = result[key]['recall_score']
result[key]['f1-score'] = result[key]['f1_score']
del result[key]['precision_score']
del result[key]['recall_score']
del result[key]['f1_score']
print(result)
```
输出:
```
{
'0': {'precision': 0.95, 'recall': 0.96, 'f1-score': 0.96, 'support': 10762.0},
'1': {'precision': 0.91, 'recall': 0.95, 'f1-score': 0.93, 'support': 9339.0},
'2': {'precision': 0.9, 'recall': 0.59, 'f1-score': 0.71, 'support': 1628.0},
'micro avg': {'precision': 0.93, 'recall': 0.93, 'f1-score': 0.93, 'support': 21729.0},
'macro avg': {'precision': 0.92, 'recall': 0.83, 'f1-score': 0.87, 'support': 21729.0},
'weighted avg': {'precision': 0.93, 'recall': 0.93, 'f1-score': 0.93, 'support': 21729.0},
'samples avg': {'precision': 0.93, 'recall': 0.93, 'f1-score': 0.93, 'support': 21729.0}
}
```
这里同样使用了正则表达式来提取键值对,并将它们转换成字典形式。由于你想要的字典形式中每个类别都有自己的字典,因此我们需要对提取的键值对进行一些处理。我们首先判断是否是一个类别对应的键值对,如果是,就将其添加到对应类别的字典中。我们还需要添加其他信息,例如'support'、'precision'、'recall'和'f1-score',并删除多余的键。
阅读全文