gpt4 book ai didi

python - 我怎样才能在 python 中整齐地处理几个正则表达式案例

转载 作者:太空狗 更新时间:2023-10-30 01:30:24 25 4
gpt4 key购买 nike

所以我在 python 中获得了一些输入,我需要使用正则表达式进行解析。

目前我正在使用这样的东西:

matchOK = re.compile(r'^OK\s+(\w+)\s+(\w+)$')
matchFailed = re.compile(r'^FAILED\s(\w+)$')
#.... a bunch more regexps

for l in big_input:
match = matchOK.search(l)
if match:
#do something with match
continue
match = matchFailed.search(l)
if match:
#do something with match
continue
#.... a bunch more of these
# Then some error handling if nothing matches

现在我通常喜欢 python,因为它简洁明了。但这感觉很冗长。我希望能够做这样的事情:

for l in big_input:      
if match = matchOK.search(l):
#do something with match
elif match = matchFailed.search(l):
#do something with match
#.... a bunch more of these
else
# error handling

我是不是遗漏了什么,或者第一个表格是否和我要得到的一样整洁?

最佳答案

class helper:
def __call__(self, match):
self.match= match
return bool(match)

h= helper()
for l in big_input:
if h(matchOK.search(l)):
# do something with h.match
elif h(matchFailed.search(l)):
# do something with h.match
... # a bunch more of these
else:
# error handling

或者匹配器作为类方法:

class matcher:
def __init__(self):
# compile matchers
self.ok= ...
self.failed= ...
self....= ...

def matchOK(self, l):
self.match= self.ok(l)
return bool(self.match)

def matchFailed(self, l):
self.match= self.failed(l)
return bool(self.match)

def match...(self, l):
...

m= matcher()
for l in big_input:
if m.matchOK(l):
# do something with m.match
elif m.matchFailed(l):
# do something with m.match
... # a bunch more of these
else:
# error handling

关于python - 我怎样才能在 python 中整齐地处理几个正则表达式案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5510879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com