python - 如何使用正则表达式从列表中填充字典?
问题描述
我有一个列表(“输出”)。我想从中提取值并将它们放入字典中。到目前为止,我可以使用正则表达式提取一些单词。但我不知道如何填写字典。
这是我的尝试
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)
解决方案
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'}
推荐阅读
- c# - 从 C# 表单中的某个位置获取颜色
- postgresql - PostgreSQL中的多次时间点恢复
- java - 将“java.lang.String”转换为所需类型“javax.servlet.http.Part”
- angular - 无法导航到另一个组件 - Angular
- deep-learning - 用于延时学习环境配置的深度强化学习
- python - 如何过滤掉包含某些字符串的“set”类型值的pandas df行?
- c# - 在 Xamarin.Forms iOS 中,获取 HttpRequestException:锁定设备时发送请求时出错
- bash - Docker 中的 WebLogic:如何自动启动托管服务器
- c - 通过访问禁止的内存位置注入内存异常
- java - apache pdfbox - 如何测试文档是否被展平?