gpt4 book ai didi

python - 在代表 python 中大文件的大字符串上加速 re.sub()?

转载 作者:行者123 更新时间:2023-12-05 09:01:10 25 4
gpt4 key购买 nike

您好,我正在运行此 python 代码以将多行模式减少为单例,但是,我正在对超过 200,000 行的超大文件执行此操作。

这是我当前的代码:

import sys
import re

with open('largefile.txt', 'r+') as file:
string = file.read()
string = re.sub(r"((?:^.*\n)+)(?=\1)", "", string, flags=re.MULTILINE)
file.seek(0)
file.write(string)
file.truncate()

问题是 re.sub() 在我的大文件上花费了很长时间 (10m+)。是否有可能以任何方式加快速度?

示例输入文件:

hello
mister
hello
mister
goomba
bananas
goomba
bananas
chocolate
hello
mister

示例输出:

hello
mister
goomba
bananas
chocolate
hello
mister

这些图案也可以大于 2 行。

最佳答案

正则表达式在这里很紧凑,但永远不会很快。出于一个原因,您有一个固有的基于行的问题,但正则表达式本质上是基于字符的。正则表达式引擎必须一次又一次地通过搜索换行符来推断“行”在哪里。出于更根本的原因,这里的所有内容都是一次一个字符的蛮力搜索,从一个阶段到下一个阶段什么都不记得。

所以这里有一个替代方案。将巨大的字符串拆分成一个行列表,只在开始时一次。那么这项工作就不需要再做一次了。然后构建一个字典,将一行映射到该行出现的索引列表。这需要线性时间。然后,给定一条线,我们根本不需要搜索它:索引列表立即告诉我们它出现的每个地方。

最坏情况下的时间可能仍然很差,但我预计它在“典型”输入上至少会快一百倍。

def dedup(s):
from collections import defaultdict

lines = s.splitlines(keepends=True)
line2ix = defaultdict(list)
for i, line in enumerate(lines):
line2ix[line].append(i)
out = []
n = len(lines)
i = 0
while i < n:
line = lines[i]
# Look for longest adjacent match between i:j and j:j+(j-i).
# j must be > i, and j+(j-i) <= n so that j <= (n+i)/2.
maxj = (n + i) // 2
searching = True
for j in reversed(line2ix[line]):
if j > maxj:
continue
if j <= i:
break
# Lines at i and j match.
if all(lines[i + k] == lines[j + k]
for k in range(1, j - i)):
searching = False
break
if searching:
out.append(line)
i += 1
else: # skip the repeated block at i:j
i = j
return "".join(out)

编辑

这结合了 Kelly 使用 deque 增量更新 line2ix 的想法,以便查看的候选人始终在 range(i+1, maxj+1) 。然后最内层的循环不需要检查这些条件。

这是一个混合包,当重复项很少时会丢失一点,因为在这种情况下 line2ix 序列非常短(对于独特的行甚至是单例)。

这是一个真正值得的案例的时机:一个包含大约 30,000 行 Python 代码的文件。许多行是独一无二的,但有几种行很常见(例如,空的 "\n" 行)。削减最内层循环中的工作可以支付那些公共(public)线路的费用。选择 dedup_nuts 作为名称是因为这种级别的微优化非常疯狂 ;-)

71.67997950001154 dedup_original
48.948923900024965 dedup_blhsing
2.204853900009766 dedup_Tim
9.623824400012381 dedup_Kelly
1.0341253000078723 dedup_blhsingTimKelly
0.8434303000103682 dedup_nuts

还有代码:

def dedup_nuts(s):
from array import array
from collections import deque

encode = {}
decode = []
lines = array('L')
for line in s.splitlines(keepends=True):
if (code := encode.get(line)) is None:
code = encode[line] = len(encode)
decode.append(line)
lines.append(code)
del encode
line2ix = [deque() for line in lines]
view = memoryview(lines)
out = []
n = len(lines)
i = 0
last_maxj = -1
while i < n:
maxj = (n + i) // 2
for j in range(last_maxj + 1, maxj + 1):
line2ix[lines[j]].appendleft(j)
last_maxj = maxj
line = lines[i]
js = line2ix[line]
assert js[-1] == i, (i, n, js)
js.pop()
for j in js:
#assert i < j <= maxj
if view[i : j] == view[j : j + j - i]:
for k in range(i + 1, j):
js = line2ix[lines[k]]
assert js[-1] == k, (i, k, js)
js.pop()
i = j
break
else:
out.append(line)
i += 1
#assert all(not d for d in line2ix)
return "".join(map(decode.__getitem__, out))

一些关键的不变量由那里的断言检查,但昂贵的不变量被注释掉以提高速度。调味。

关于python - 在代表 python 中大文件的大字符串上加速 re.sub()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73956255/

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