like中有函数吗关于芬德尔但那会返回字典而不是元组?

2024-06-26 00:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这根绳子:

a= "hello world hella warld"

我想把所有的巧合与正则表达式匹配:

^{pr2}$

我可以用关于芬德尔(b,a)得到:

[('hello', 'world'),('hella','warld')]

但我真的想得到:

[{'hel':'hello','wrl':'world'},{'hel':'hella','wrl':'warld'}]

在Python中有没有一些本地的或者简单的方法来获得这个?在

第二个问题:

我写了一个函数来获取字典:

def findalldict(regex,line):
    matches = []
    match = 1
    c = line
    while match != None and len(c)>1:
        match =re.search(regex,c)
        if match:
            matches.append(match.groupdict())
            c =c[match.end():]
    return matches

但我不确定它是否正确,你们能看出什么错误吗?或者你知道更好的方法来完成这个?在


Tags: 方法函数helloworld字典matchlineregex
1条回答
网友
1楼 · 发布于 2024-06-26 00:27:30

您可以使用^{}代替findall来获得^{}的迭代器:

>>> regex = re.compile('(?P<hel>hell[oa])\s*(?P<wrl>w[oa]rld)')
>>> line = "hello world hella warld"
>>> [m.groupdict() for m in regex.finditer(line)]
[{'hel': 'hello', 'wrl': 'world'}, {'hel': 'hella', 'wrl': 'warld'}]

相关问题 更多 >