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

您好,我正在运行此 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))

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

https://stackoverflow.com/questions/73956255/

相关文章:

c# - 在 C# 中将小驼峰命名法转换为 PascalCase?

Python - 如何删除以数字开头并包含句点的单词

bash - 使用 sed 删除算术形式

c++ - 如何在 SSE2 中为 8 位和 16 位整数实现 vector 右移和左移?

rust - Rust 中的一个可变借用或多个不可变借用……为什么?

ruby - 如何在 Ruby 中创建可调用属性

c++ - 你能用折叠表达式实现 fn(x1 ^ fn(x0)) 吗?

python - 在python中打印出两个列表的组合

go - gcloud 函数部署 go 运行时错误 "undefined: unsafe.Slice

regex - 为什么 Perl 正则表达式不匹配 "\n"和后面的字符?