【发布时间】:2025-12-02 23:45:01
【问题描述】:
我有一个列表(“输出”)。我想从中提取值并将它们放入字典中。 到目前为止,我可以使用正则表达式提取一些单词。但是我不知道怎么填字典。
这是我的尝试
output = ['labels: imagenet_labels.txt \n', '\n', 'Model: efficientnet-edgetpu-S_quant_edgetpu.tflite \n', '\n', 'Image: img0000.jpg \n', '\n', '----INFERENCE TIME----\n', 'Note: The first inference on Edge TPU is slow because it includes loading the model into Edge TPU memory.\n', 'time: 6.0ms\n', '-------RESULTS--------\n','results: wall clock\n', 'score: 0.25781\n', '##################################### \n', ' \n', '\n']
mydict = {}
regex1 = re.compile(fr'(\w+:)\s(.*)')
match_regex1 = list(filter(regex1.match, output))
match = [line.rstrip('\n') for line in match_regex1]
字典必须如下所示:
{
'Model': "efficientnet-edgetpu-S_quant_edgetpu.tflite",
'Image': "img0000.jpg",
'time': "6.0",
'results': "wall_clock",
'score': :0.25781"
}
列表如下所示:
编辑
我已经做了这个循环。尽管它不能正常工作:
for i in output:
reg1 = re.search(r'(\w+:)\s(.*)', i)
if "Model" in i:
mydict.setdefault("Model", {reg1.group()})
print(mydict)
【问题讨论】:
-
字典不显示
'labels: imagenet_labels.txt。这是故意的吗? -
是的,没有必要。我可以从列表中删除它。
标签: python regex list dictionary