re.findall 返回命名捕获组的字典? [英] re.findall which returns a dict of named capturing groups?

查看:36
本文介绍了re.findall 返回命名捕获组的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

灵感来自一个现已删除的问题;给定一个带有命名组的正则表达式,是否有类似 findall 的方法返回带有命名捕获组的 dict 列表而不是 tuple 列表>?

给定:

<预><代码>>>>进口重新>>>text = "鲍勃·苏·乔恩·理查德·哈里">>>pat = re.compile('(?P[a-z]+)\s+(?P[a-z]+)')>>>pat.findall(文本)[('bob', 'sue'), ('jon', 'richard')]

应该改为:

[{'name': 'bob', 'name2': 'sue'}, {'name': 'jon', 'name2': 'richard'}]

解决方案

>>>进口重新>>>s = "鲍勃·苏·乔恩·理查德·哈里">>>r = re.compile('(?P[a-z]+)\s+(?P[a-z]+)')>>>[m.groupdict() for m in r.finditer(s)][{'name2': 'sue', 'name': 'bob'}, {'name2': 'richard', 'name': 'jon'}]

Inspired by a now-deleted question; given a regex with named groups, is there a method like findall which returns a list of dict with the named capturing groups instead of a list of tuple?

Given:

>>> import re
>>> text = "bob sue jon richard harry"
>>> pat = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)')
>>> pat.findall(text)
[('bob', 'sue'), ('jon', 'richard')]

Should instead give:

[{'name': 'bob', 'name2': 'sue'}, {'name': 'jon', 'name2': 'richard'}]

解决方案

>>> import re
>>> s = "bob sue jon richard harry"
>>> r = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)')
>>> [m.groupdict() for m in r.finditer(s)]
[{'name2': 'sue', 'name': 'bob'}, {'name2': 'richard', 'name': 'jon'}]

这篇关于re.findall 返回命名捕获组的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆