【问题标题】:How to fill a dictionary from a list using regex?如何使用正则表达式从列表中填充字典?
【发布时间】: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


【解决方案1】:

你可以试试这个,根据match列表:

import re
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]

features_wanted='ModelImagetimeresultsscore'

dct={i.replace(' ','').split(':')[0]:i.replace(' ','').split(':')[1] for i in match if i.replace(' ','').split(':')[0] in features_wanted}
mydict=dct
print(dct)

输出:

{'Model': 'efficientnet-edgetpu-S_quant_edgetpu.tflite', 'Image': 'img0000.jpg', 'time': '6.0ms', 'results': 'wallclock', 'score': '0.25781'}

dct 的解释:这是一个Dictionary Comprehension 并迭代列表匹配,所以这里是一个使用'Model: efficientnet-edgetpu-S_quant_edgetpu.tflite' 的迭代示例:

#First check if it is a feature wanted:
i='Model: efficientnet-edgetpu-S_quant_edgetpu.tflite'
i.replace(' ','')
>>>'Model:efficientnet-edgetpu-S_quant_edgetpu.tflite'
i.replace(' ','').split(':')
>>>['Model','efficientnet-edgetpu-S_quant_edgetpu.tflite']
i.replace(' ','').split(':')[0] in features_wanted  #'Model' in 'ModelImagetimeresultsscore'
>>>True
#If it is in features_wanted, an item like this is append to the dictionary:
i.replace(' ','').split(':')[0]:i.replace(' ','').split(':')[1]
>>>'Model':'efficientnet-edgetpu-S_quant_edgetpu.tflite'

【讨论】:

  • 你能解释一下:“dct = ...”吗?
  • 好的,刚刚加了个解释,希望清楚。
【解决方案2】:

要填写字典,您可以使用此脚本:

for item in match:
    key , value = item.split(":")
    mydict[key] = value

所以结果是这样的:

{'labels': ' imagenet_labels.txt ', 'Model': ' efficientnet-edgetpu-S_quant_edgetpu.tflite ', 'Image': ' img0000.jpg ', 'Note': ' The first inference on Edge TPU is slow because it includes loading the model into Edge TPU memory.', 'time': ' 6.0ms', 'results': ' wall clock', 'score': ' 0.25781'}

【讨论】:

    【解决方案3】:
    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']
    
    d = dict( re.findall(r'(\w+):\s*([^\n]+?)\s*$', ' '.join(output), flags=re.M) )
    
    from pprint import pprint
    pprint(d)
    

    打印:

    {'Image': 'img0000.jpg',
     'Model': 'efficientnet-edgetpu-S_quant_edgetpu.tflite',
     'Note': 'The first inference on Edge TPU is slow because it includes loading '
             'the model into Edge TPU memory.',
     'labels': 'imagenet_labels.txt',
     'results': 'wall clock',
     'score': '0.25781',
     'time': '6.0ms'}
    

    【讨论】:

    • OP 使用re.match,所以你需要^re.findall 模式。使用r'^(\w+):\s*(.*\S)'r'^(\w+):[^\S\n]*(.*\S)'(因为\s 匹配换行符)。
    • @WiktorStribiżew 当我使用d = dict( re.findall(r'^(\w+):\s*(.*\S)', ' '.join(output), flags=re.M) ) 时,输出只是{'labels': 'imagenet_labels.txt'}
    【解决方案4】:

    由于字段的分隔符始终为:,因此您可以使用str.split 方法代替正则表达式以提高效率:

    dict(s.split(': ', 1) for s in map(str.rstrip, output) if ': ' in s)
    

    演示:https://repl.it/@blhsing/SnoopyBoringComputationalscience

    【讨论】:

    • 如果“输出”更大,它将如何变化?我的意思是如果有很多“模型:”、“图像:”等?