gpt4 book ai didi

python - 在 python 中使用 re.search 时执行时间增加

转载 作者:太空宇宙 更新时间:2023-11-04 10:48:48 25 4
gpt4 key购买 nike

我正在处理一个 500MB 的文件。使用研究时处理时间增加。

请找出我测试过的以下案例。在所有情况下,我都是逐行读取文件并仅使用一个 if 条件。

案例一:

prnt = re.compile(r"(?i)<spanlevel level='7'>")
if prnt.search(line):
print "Matched"
out_file.write(line)
else:
out_file.write(line)

读取整个文件用了 16 秒。

案例2:

if re.search(r"(?i)<spanlevel level='7'>",line):
print "Matched"
out_file.write(line)
else:
out_file.write(line)

读取文件需要 25 秒。

案例3:

if "<spanlevel level='7'>" in line:
print "Matched"
out_file.write(line)
else:
out_file.write(line)

读取文件只用了 8 秒。

你们中的任何人都可以告诉这三种情况之间的区别吗? Case3 的处理速度非常快,但我无法进行不区分大小写的匹配。如何在 Case3 中进行不区分大小写的匹配?

最佳答案

不区分大小写首先搜索案例 3:

if "<spanlevel level='7'>" in line.lower():

通过小写 line,您可以进行小写搜索。

至于为什么情况 2 慢得多:使用预编译的正则表达式会更快,因为您可以避免为从文件中读取的每一行的正则表达式模式进行缓存查找。在引擎盖下,如果不存在缓存副本,re.search() 也会调用 re.compile(),并且额外的函数调用和缓存检查将花费您.

这在 Python 3.3 上是双重痛苦的,它使用 functools.lru_cache decorator 切换到一个新的缓存模型。 ,实际上比以前的实现要慢。参见 Why are uncompiled, repeatedly used regexes so much slower in Python 3?

使用 in 的简单文本搜索对于精确文本匹配更快。正则表达式非常适合复杂匹配,您只是在寻找精确匹配,尽管不区分大小写。

关于python - 在 python 中使用 re.search 时执行时间增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15481821/

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