gpt4 book ai didi

Python字符串搜索效率

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

对于非常大的字符串(跨越多行),使用 Python 的内置字符串搜索还是拆分大字符串(可能在 \n 上)并迭代搜索较小的字符串更快?

例如,对于非常大的字符串:

for l in get_mother_of_all_strings().split('\n'):
if 'target' in l:
return True
return False

return 'target' in get_mother_of_all_strings()

最佳答案

可能 当然是第二种,我看不出在大字符串中搜索或在小字符串中搜索有什么不同。由于行较短,您可能会跳过一些字符,但拆分操作也有其成本(搜索 \n,创建 n 个不同的字符串,创建列表)并且循环是在 python 中完成的。

字符串 __contain__ 方法是用 C 语言实现的,因此速度明显更快。

还要考虑到,一旦找到第一个匹配项,第二种方法就会中止,但第一个方法甚至在开始在其中搜索之前就拆分所有字符串。

这可以通过一个简单的基准快速证明:

import timeit

prepare = """
with open('bible.txt') as fh:
text = fh.read()
"""

presplit_prepare = """
with open('bible.txt') as fh:
text = fh.read()
lines = text.split('\\n')
"""

longsearch = """
'hello' in text
"""

splitsearch = """
for line in text.split('\\n'):
if 'hello' in line:
break
"""

presplitsearch = """
for line in lines:
if 'hello' in line:
break
"""


benchmark = timeit.Timer(longsearch, prepare)
print "IN on big string takes:", benchmark.timeit(1000), "seconds"

benchmark = timeit.Timer(splitsearch, prepare)
print "IN on splitted string takes:", benchmark.timeit(1000), "seconds"

benchmark = timeit.Timer(presplitsearch, presplit_prepare)
print "IN on pre-splitted string takes:", benchmark.timeit(1000), "seconds"

结果是:

IN on big string takes: 4.27126097679 seconds
IN on splitted string takes: 35.9622690678 seconds
IN on pre-splitted string takes: 11.815297842 seconds

bible.txt 文件实际上圣经,我在这里找到它:http://patriot.net/~bmcgin/kjvpage.html (文字版)

关于Python字符串搜索效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6963236/

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