gpt4 book ai didi

python - 在 Python 循环中重复使用正则表达式的最有效方法是什么?

转载 作者:行者123 更新时间:2023-11-28 19:59:41 25 4
gpt4 key购买 nike

当您迭代文件中的数百行时,在 Python 中运行正则表达式最(和最不)有效的方法是什么?

具体来说,以下是错误的形式吗?

for line in file:
data = re.search('(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)',line)
one = data.group(1)
two = data.group(2)
three = data.group(3)
four = data.group(4)
five = data.group(5)
six = data.group(6)
# do the magic...

最佳答案

如果您只是反复使用同一个正则表达式,则不需要直接编译它。 http://docs.python.org/release/2.6.5/library/re.html#re.compile

The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

但是,我强烈建议您不要像现在这样做下面的作业。尝试这样的事情:

for line in file:
data = re.search('(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)',line)
groups = data.groups()
# do the magic...

MatchObject.groups()返回匹配中所有组的元组,不参与匹配的组被分配传递给 groups() 的值(所述值默认为 None )。

关于python - 在 Python 循环中重复使用正则表达式的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3266134/

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